Example usage for org.hibernate Criteria setCacheable

List of usage examples for org.hibernate Criteria setCacheable

Introduction

In this page you can find the example usage for org.hibernate Criteria setCacheable.

Prototype

public Criteria setCacheable(boolean cacheable);

Source Link

Document

Enable caching of this query result, provided query caching is enabled for the underlying session factory.

Usage

From source file:org.jadira.usertype.dateandtime.joda.TestPersistentDateTimeWithZone.java

License:Apache License

@Test
public void testPersist() {

    EntityManager manager = factory.createEntityManager();

    manager.getTransaction().begin();/*from  w w  w  .  j  av a  2  s.  c om*/

    for (int i = 0; i < dateTimes.length; i++) {

        JodaDateTimeWithZoneHolder item = new JodaDateTimeWithZoneHolder();
        item.setId(i);
        item.setName("test_" + i);
        item.setDateTime(dateTimes[i]);

        manager.persist(item);
    }

    manager.flush();

    manager.getTransaction().commit();

    Criteria criteria = ((Session) (manager.getDelegate())).createCriteria(JodaDateTimeWithZoneHolder.class);
    criteria.setCacheable(true);
    criteria.add(Restrictions.le("dateTime.datetime", new DateTime()));
    @SuppressWarnings({ "unused", "unchecked" })
    List<JodaDateTimeWithZoneHolder> result = (List<JodaDateTimeWithZoneHolder>) criteria.list();

    manager.close();

    manager = factory.createEntityManager();

    for (int i = 0; i < dateTimes.length; i++) {

        JodaDateTimeWithZoneHolder item = manager.find(JodaDateTimeWithZoneHolder.class, Long.valueOf(i));

        assertNotNull(item);
        assertEquals(i, item.getId());
        assertEquals("test_" + i, item.getName());
        if (dateTimes[i] == null) {
            assertNull(item.getDateTime());
        } else {
            assertEquals(dateTimes[i].toString(), item.getDateTime().toString());
        }
    }

    verifyDatabaseTable(manager, JodaDateTimeWithZoneHolder.class.getAnnotation(Table.class).name());

    // Ensure use of criteria does not throw exception
    criteria = ((Session) (manager.getDelegate())).createCriteria(JodaDateTimeWithZoneHolder.class);
    criteria.setCacheable(true);
    criteria.add(Restrictions.le("dateTime.datetime", new LocalDateTime()));
    result = (List<JodaDateTimeWithZoneHolder>) criteria.list();

    manager.close();
}

From source file:org.jdal.dao.hibernate.HibernateDao.java

License:Apache License

/**
 * Get Page, apply filter if any./*from w  ww  .j ava 2 s  . c  o m*/
 * If Filter is a entity model, use Example to create a criteria.
 * else enable filter by name on session. 
 * @param page with page definitions
 * @return page of results
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <K> Page<K> getPage(Page<K> page) {

    List data = null;
    // try named query
    Query query = getQuery(page);
    if (query != null) {
        data = query.list();
    } else {
        // try filter, example and criteria builders
        Criteria criteria = getCriteria(page);
        ResultTransformer rt = ((CriteriaImpl) criteria).getResultTransformer();
        criteria.setProjection(Projections.rowCount());
        page.setCount(((Long) criteria.uniqueResult()).intValue());
        // reset criteria
        criteria.setProjection(null);
        criteria.setResultTransformer(rt);
        // set start index and page size
        criteria.setFirstResult(page.getStartIndex()).setMaxResults(page.getPageSize());
        applyOrder(page, criteria);
        // run it
        criteria.setCacheable(cachePageQueries);
        data = criteria.list();
    }

    page.setData(data);

    return page;
}

From source file:org.opensingular.flow.persistence.service.AbstractHibernatePersistenceService.java

License:Apache License

public List<PROCESS_INSTANCE> retrieveProcessInstancesWith(PROCESS_DEF process, SUser creatingUser,
        Boolean active) {/*from   w  ww.j av a 2s.co m*/
    Objects.requireNonNull(process);
    Criteria c = getSession().createCriteria(getClassProcessInstance(), "PI");
    c.createAlias("PI.processVersion", "DEF");
    c.add(Restrictions.eq("DEF.processDefinition", process));

    if (active != null) {
        DetachedCriteria sub = DetachedCriteria.forClass(getClassTaskInstance(), "T");
        sub.createAlias("T.task", "TA");
        sub.add(Restrictions.eqProperty("T.processInstance.cod", "PI.cod"));
        sub.add(Restrictions.isNull("T.endDate"));
        if (active) {
            sub.add(Restrictions.ne("TA.type", TaskType.END));
        } else {
            sub.add(Restrictions.eq("TA.type", TaskType.END));
        }
        sub.setProjection(Projections.id());

        c.add(Subqueries.exists(sub));
    }

    if (creatingUser != null) {
        c.add(Restrictions.eq("PI.userCreator", creatingUser));
    }
    c.setCacheable(true).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return c.list();
}

From source file:org.openspaces.persistency.hibernate.iterator.DefaultCriteriaByExampleDataIterator.java

License:Open Source License

protected Iterator createIterator() {
    session = sessionFactory.openSession();
    transaction = session.beginTransaction();
    Example example = Example.create(template);
    Criteria criteria = session.createCriteria(template.getClass()).add(example);
    criteria.setCacheMode(CacheMode.IGNORE);
    criteria.setCacheable(false);
    criteria.setFlushMode(FlushMode.NEVER);
    return criteria.list().iterator();
}

From source file:org.openspaces.persistency.hibernate.iterator.DefaultListQueryDataIterator.java

License:Open Source License

protected Iterator createIterator() {
    session = sessionFactory.openSession();
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setCacheMode(CacheMode.IGNORE);
        criteria.setCacheable(false);
        criteria.setFlushMode(FlushMode.NEVER);
        if (from >= 0) {
            criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }//from  ww  w  . j a  v a2s . co  m
        return criteria.list().iterator();
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        if (from >= 0) {
            query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.list().iterator();
    } else if (dataSourceSQLQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromDataSourceSQLQuery(dataSourceSQLQuery, session);
        if (from >= 0) {
            query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.list().iterator();
    } else {
        throw new IllegalStateException("Either SQLQuery or entity must be provided");
    }
}

From source file:org.openspaces.persistency.hibernate.iterator.DefaultScrollableDataIterator.java

License:Open Source License

protected ScrollableResults createCursor() {
    session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setCacheable(false);
        criteria.setFlushMode(FlushMode.MANUAL);
        criteria.setFetchSize(fetchSize);
        if (perfromOrderById) {
            ClassMetadata metadata = sessionFactory.getClassMetadata(entityName);
            String idPropName = metadata.getIdentifierPropertyName();
            if (idPropName != null) {
                criteria.addOrder(Order.asc(idPropName));
            }/*from  w w w . j  a  v a  2  s .  c  o m*/
        }
        if (from >= 0) {
            if (from > 0)
                criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }
        return criteria.scroll(ScrollMode.FORWARD_ONLY);
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else if (hQuery != null) {
        Query query = session.createQuery(hQuery);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        query.setCacheMode(CacheMode.IGNORE);
        query.setCacheable(false);
        query.setReadOnly(true);
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else {
        throw new IllegalStateException("No SQLQuery, entity, or Hibernate Query provided");
    }
}

From source file:org.openspaces.persistency.hibernate.iterator.StatelessListQueryDataIterator.java

License:Open Source License

protected Iterator createIterator() {
    session = sessionFactory.openStatelessSession();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setCacheable(false);
        if (from >= 0) {
            criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }/* ww  w  . ja  va  2s .  com*/
        return criteria.list().iterator();
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        if (from >= 0) {
            query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.list().iterator();
    } else if (dataSourceSQLQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromDataSourceSQLQuery(dataSourceSQLQuery, session);
        if (from >= 0) {
            query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.list().iterator();
    } else {
        throw new IllegalStateException("Either SQLQuery or entity must be provided");
    }
}

From source file:org.osiam.storage.dao.GetInternalIdSkeleton.java

License:Open Source License

protected <T> SCIMSearchResult<T> search(Class<T> clazz, String filter, int count, int startIndex,
        String sortBy, String sortOrder) {
    Session session = (Session) em.getDelegate();
    Criteria criteria = session.createCriteria(clazz);
    criteria.setReadOnly(true);// w ww.ja  va  2  s .c om
    criteria.setCacheMode(CacheMode.GET);
    criteria.setCacheable(true);
    if (filter != null && !filter.isEmpty()) {
        criteria = criteria.add(filterParser.parse(filter).buildCriterion());
    }
    createAliasesForCriteria(criteria);
    criteria.setMaxResults(count);
    long totalResult = getTotalResults(criteria);
    setSortOrder(sortBy, sortOrder, criteria);
    criteria.setFirstResult(startIndex);
    Criteria criteria1 = criteria.setProjection(null).setResultTransformer(Criteria.ROOT_ENTITY);
    List list = criteria1.list();
    return new SCIMSearchResult(list, totalResult);
}

From source file:org.picketlink.idm.impl.store.hibernate.HibernateIdentityStoreImpl.java

License:Open Source License

public Criteria prepareResolveRelationshipsCriteria(IdentityStoreInvocationContext ctx, IdentityObject identity,
        IdentityObjectRelationshipType type, boolean parent, boolean named, String name,
        IdentityObjectSearchCriteria searchCriteria) throws IdentityException {
    HibernateIdentityObject hio = safeGet(ctx, identity);

    Criteria criteria = getHibernateSession(ctx).createCriteria(HibernateIdentityObjectRelationship.class);
    criteria.setCacheable(true);

    if (type != null) {
        HibernateIdentityObjectRelationshipType hibernateType = getHibernateIdentityObjectRelationshipType(ctx,
                type);//from   ww  w  .  j  a  va  2s . c o m

        criteria.add(Restrictions.eq("type", hibernateType));
    }

    if (name != null) {
        criteria.add(Restrictions.eq("name.name", name));
    } else if (named) {
        criteria.add(Restrictions.isNotNull("name"));
    } else {
        criteria.add(Restrictions.isNull("name"));
    }

    if (parent) {
        criteria.add(Restrictions.eq("fromIdentityObject", hio));
    } else {
        criteria.add(Restrictions.eq("toIdentityObject", hio));
    }

    criteria.setFetchMode("fromIdentityObject", FetchMode.JOIN);
    criteria.setFetchMode("toIdentityObject", FetchMode.JOIN);

    if (searchCriteria != null && searchCriteria.isPaged() && !searchCriteria.isFiltered()) {
        if (searchCriteria.getMaxResults() > 0) {
            criteria.setMaxResults(searchCriteria.getMaxResults());
        }
        criteria.setFirstResult(searchCriteria.getFirstResult());
    }

    if (searchCriteria != null && searchCriteria.isSorted()) {
        if (parent) {
            criteria.createAlias("toIdentityObject", "io");
            if (searchCriteria.isAscending()) {
                criteria.addOrder(Order.asc("io.name"));
            } else {
                criteria.addOrder(Order.desc("io.name"));
            }
        } else {
            criteria.createAlias("fromIdentityObject", "io");
            if (searchCriteria.isAscending()) {
                criteria.addOrder(Order.asc("io.name"));
            } else {
                criteria.addOrder(Order.desc("io.name"));
            }
        }
    }

    return criteria;
}

From source file:org.projectforge.core.BaseDao.java

License:Open Source License

@SuppressWarnings("unchecked")
private void getHistoryEntries(final Session session, final BaseSearchFilter filter, final Set<Integer> idSet,
        final Class<?> clazz, final boolean searchStringInHistory) {
    if (log.isDebugEnabled() == true) {
        log.debug("Searching in " + clazz);
    }/*from w  w w.ja v  a  2  s .c o  m*/
    // First get all history entries matching the filter and the given class.
    final String className = ClassUtils.getShortClassName(clazz);
    if (searchStringInHistory == true) {
        final StringBuffer buf = new StringBuffer();
        buf.append("(+className:").append(className);
        if (filter.getStartTimeOfModification() != null || filter.getStopTimeOfModification() != null) {
            final DateFormat df = new SimpleDateFormat(DateFormats.LUCENE_TIMESTAMP_MINUTE);
            df.setTimeZone(DateHelper.UTC);
            buf.append(" +timestamp:[");
            if (filter.getStartTimeOfModification() != null) {
                buf.append(df.format(filter.getStartTimeOfModification()));
            } else {
                buf.append("000000000000");
            }
            buf.append(" TO ");
            if (filter.getStopTimeOfModification() != null) {
                buf.append(df.format(filter.getStopTimeOfModification()));
            } else {
                buf.append("999999999999");
            }
            buf.append("]");
        }
        if (filter.getModifiedByUserId() != null) {
            buf.append(" +userName:").append(filter.getModifiedByUserId());
        }
        buf.append(") AND (");
        final String searchString = buf.toString() + modifySearchString(filter.getSearchString()) + ")";
        try {
            final FullTextSession fullTextSession = Search.getFullTextSession(getSession());
            final org.apache.lucene.search.Query query = createFullTextQuery(HISTORY_SEARCH_FIELDS, null,
                    searchString);
            if (query == null) {
                // An error occured:
                return;
            }
            final FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, HistoryEntry.class);
            fullTextQuery.setCacheable(true);
            fullTextQuery.setCacheRegion("historyItemCache");
            fullTextQuery.setProjection("entityId");
            final List<Object[]> result = fullTextQuery.list();
            if (result != null && result.size() > 0) {
                for (final Object[] oa : result) {
                    idSet.add((Integer) oa[0]);
                }
            }
        } catch (final Exception ex) {
            final String errorMsg = "Lucene error message: " + ex.getMessage() + " (for "
                    + this.getClass().getSimpleName() + ": " + searchString + ").";
            filter.setErrorMessage(errorMsg);
            log.info(errorMsg);
        }
    } else {
        final Criteria criteria = session.createCriteria(HistoryEntry.class);
        setCacheRegion(criteria);
        criteria.add(Restrictions.eq("className", className));
        if (filter.getStartTimeOfModification() != null && filter.getStopTimeOfModification() != null) {
            criteria.add(Restrictions.between("timestamp", filter.getStartTimeOfModification(),
                    filter.getStopTimeOfModification()));
        } else if (filter.getStartTimeOfModification() != null) {
            criteria.add(Restrictions.ge("timestamp", filter.getStartTimeOfModification()));
        } else if (filter.getStopTimeOfModification() != null) {
            criteria.add(Restrictions.le("timestamp", filter.getStopTimeOfModification()));
        }
        if (filter.getModifiedByUserId() != null) {
            criteria.add(Restrictions.eq("userName", filter.getModifiedByUserId().toString()));
        }
        criteria.setCacheable(true);
        criteria.setCacheRegion("historyItemCache");
        criteria.setProjection(Projections.property("entityId"));
        final List<Integer> idList = criteria.list();
        if (idList != null && idList.size() > 0) {
            for (final Integer id : idList) {
                idSet.add(id);
            }
        }
    }
}