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:br.com.thiaguten.persistence.spi.provider.hibernate.HibernatePersistenceProvider.java

License:Apache License

/**
 * {@inheritDoc}//from   ww  w. ja v a  2s .co m
 */
@Override
public <ID extends Serializable, T extends Persistable<ID>> T findUniqueResultByCriteria(Class<T> entityClazz,
        boolean cacheable, List<Criterion> criterions) {
    Criteria criteria = getSession().createCriteria(entityClazz);
    if (criterions != null) {
        for (Criterion c : criterions) {
            criteria.add(c);
        }
    }
    return (T) criteria.setCacheable(cacheable).uniqueResult();
}

From source file:br.gov.jfrj.siga.model.dao.ModeloDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> List<T> consultar(final T exemplo, final String[] excluir) {
    final Criteria crit = getSessao().createCriteria(exemplo.getClass());
    final Example example = Example.create(exemplo);
    if (excluir != null) {
        for (final String exclude : excluir) {
            example.excludeProperty(exclude);
        }/*from   w  w  w.  j av a  2s  .  c  o  m*/
    }
    crit.add(example);
    if (getCacheRegion() != null) {
        crit.setCacheable(true);
        crit.setCacheRegion(getCacheRegion());
    }
    return crit.list();
}

From source file:br.gov.jfrj.siga.model.dao.ModeloDao.java

License:Open Source License

@SuppressWarnings("unchecked")
protected <T> List<T> findAndCacheByCriteria(String cacheRegion, Class<T> clazz, final Criterion... criterion) {
    final Criteria crit = getSessao().createCriteria(clazz);
    for (final Criterion c : criterion) {
        crit.add(c);// ww  w. j  a  v a 2  s  .  c  o  m
    }
    if (cacheRegion != null) {
        crit.setCacheable(true);
        crit.setCacheRegion(cacheRegion);
    }
    return crit.list();
}

From source file:br.mdarte.exemplo.academico.cd.CursoDAO.java

public List<AbstractEntity> defaultFilter(AbstractTO to, PaginationStrategy paginacao) throws DAOException {

    Session session = currentSession();//  w ww .  jav a2s .  c  o m
    Criteria criterios = ((org.hibernate.Session) session).createCriteria(CursoImpl.class);

    if (to instanceof CursoTOImpl) {

        CursoAbstract entityAbstract;
        try {
            entityAbstract = CursoAbstract.getEntityFromTO((CursoTOImpl) to);
            criterios.add(Example.create(entityAbstract).enableLike(MatchMode.ANYWHERE));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        return null;
    }

    try {
        if (paginacao == null)
            paginacao = new NoPagination();

        paginacao.paginateResult(criterios);
        criterios.setCacheable(true);
        return criterios.list();

    } catch (HibernateException h) {
        throw new DAOException(h);
    }
}

From source file:br.mdarte.exemplo.academico.cd.EstudanteDAO.java

public List<AbstractEntity> defaultFilter(AbstractTO to, PaginationStrategy paginacao) throws DAOException {

    Session session = currentSession();/*  ww  w .ja  v  a 2 s.  c om*/
    Criteria criterios = ((org.hibernate.Session) session).createCriteria(EstudanteImpl.class);

    if (to instanceof EstudanteTOImpl) {

        EstudanteAbstract entityAbstract;
        try {
            entityAbstract = EstudanteAbstract.getEntityFromTO((EstudanteTOImpl) to);
            criterios.add(Example.create(entityAbstract).enableLike(MatchMode.ANYWHERE));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        return null;
    }

    try {
        if (paginacao == null)
            paginacao = new NoPagination();

        paginacao.paginateResult(criterios);
        criterios.setCacheable(true);
        return criterios.list();

    } catch (HibernateException h) {
        throw new DAOException(h);
    }
}

From source file:com.copyright.common.hibernate.HibernateDao.java

License:Apache License

/**
 * Criteria./*from w  w w  .j  a v a2  s  .  c o m*/
 * 
 * @param criterions
 *            ??Restrictions?,?{@link #createQuery(String,Object...)}
 */
public <T> Criteria createCriteria(Class<T> entityClass, Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(entityClass);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    return criteria.setCacheable(isCache);
}

From source file:com.eucalyptus.entities.Entities.java

License:Open Source License

private static Criteria setOptions(final Criteria criteria, final QueryOptions options) {
    final Integer maxResults = options.getMaxResults();
    if (maxResults != null) {
        criteria.setMaxResults(maxResults);
    }/*ww  w .  j ava2  s .  co m*/
    final Integer fetchSize = options.getFetchSize();
    if (fetchSize != null) {
        criteria.setFetchSize(fetchSize);
    }
    final Boolean cacheable = options.getCacheable();
    if (cacheable != null) {
        criteria.setCacheable(cacheable);
    }
    final Boolean readonly = options.getReadonly();
    if (readonly != null) {
        criteria.setReadOnly(readonly);
    }
    final Criterion criterion = options.getCriterion();
    if (criterion != null) {
        criteria.add(criterion);
    }
    return criteria;
}

From source file:com.expressui.core.dao.GenericDao.java

License:Open Source License

/**
 * Finds an entity by natural id, or business key. This method only works for entities that have a single property
 * marked as @NaturalId. The benefit of calling this method is that Hibernate will try to look up the entity
 * in the secondary cache.//from   w w  w.j av  a  2 s .  c o  m
 *
 * @param entityType    the type of entity
 * @param propertyName  the name of the property in the entity that is marked @NaturalId
 * @param propertyValue the value to search for
 * @param <T>           type of entity
 * @return found entity
 */
public <T> T findByNaturalId(Class<? extends T> entityType, String propertyName, Object propertyValue) {
    Session session = (Session) getEntityManager().getDelegate();

    Criteria criteria = session.createCriteria(entityType);
    criteria.add(Restrictions.naturalId().set(propertyName, propertyValue));
    criteria.setCacheable(true);

    return (T) criteria.uniqueResult();
}

From source file:com.gisgraphy.domain.repository.GenericGisDao.java

License:Open Source License

/**
 * base method for all findNearest* //from w  w w.  java  2s  .c o  m
 * 
 * @param point
 *                The point from which we want to find GIS Object
 * @param pointId
 *                the id of the point that we don't want to be include, it
 *                is used to not include the gisFeature from which we want
 *                to find the nearest
 * @param distance
 *                distance The radius in meters
 * @param firstResult
 *                the firstResult index (for pagination), numbered from 1,
 *                if < 1 : it will not be taken into account
 * @param maxResults
 *                The Maximum number of results to retrieve (for
 *                pagination), if <= 0 : it will not be taken into acount
 * @param requiredClass
 *                the class of the object to be retireved
 * @param isMunicipality whether we should filter on city that are flag as 'municipality'.
          act as a filter, if false it doesn't filters( false doesn't mean that we return non municipality)
 * @return A List of GisFeatureDistance with the nearest elements or an
 *         emptylist (never return null), ordered by distance.<u>note</u>
 *         the specified gisFeature will not be included into results
 * @see GisFeatureDistance
 * @return a list of gisFeature (never return null but an empty list)
 */
@SuppressWarnings("unchecked")
protected List<GisFeatureDistance> getNearestAndDistanceFrom(final Point point, final Long pointId,
        final double distance, final int firstResult, final int maxResults, final boolean includeDistanceField,
        final Class<? extends GisFeature> requiredClass, final boolean isMunicipality) {
    Assert.notNull(point);
    return (List<GisFeatureDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(requiredClass);

            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            criteria = criteria.add(new DistanceRestriction(point, distance));
            List<String> fieldList = IntrospectionHelper.getFieldsAsList(requiredClass);
            ProjectionList projections = ProjectionBean.fieldList(fieldList, true);
            if (includeDistanceField) {
                projections.add(SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME)
                        .as("distance"));
            }
            criteria.setProjection(projections);
            if (pointId != 0) {
                // remove The From Point
                criteria = criteria.add(Restrictions.not(Restrictions.idEq(pointId)));
            }
            if (includeDistanceField) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (isMunicipality && (requiredClass == City.class || requiredClass == GisFeature.class)) {
                criteria.add(Restrictions.eq(City.MUNICIPALITY_FIELD_NAME, isMunicipality));
            }

            criteria.setCacheable(true);
            List<Object[]> queryResults = criteria.list();

            String[] aliasList;
            if (includeDistanceField) {
                aliasList = (String[]) ArrayUtils.add(IntrospectionHelper.getFieldsAsArray(requiredClass),
                        "distance");
            } else {
                aliasList = IntrospectionHelper.getFieldsAsArray(requiredClass);
            }
            int idPropertyIndexInAliasList = 0;
            for (int i = 0; i < aliasList.length; i++) {
                if (aliasList[i] == "id") {
                    idPropertyIndexInAliasList = i;
                    break;
                }
            }

            boolean hasZipCodesProperty = ZipCodesAware.class.isAssignableFrom(requiredClass);
            Map<Long, Set<String>> idToZipCodesMap = null;
            if (hasZipCodesProperty && queryResults.size() > 0) {
                List<Long> ids = new ArrayList<Long>();
                for (Object[] tuple : queryResults) {
                    ids.add((Long) tuple[idPropertyIndexInAliasList]);
                }
                String zipCodeQuery = "SELECT code as code,gisfeature as id FROM "
                        + ZipCode.class.getSimpleName().toLowerCase() + " zip where zip.gisfeature in (:ids)";
                Query qry = session.createSQLQuery(zipCodeQuery).addScalar("code", Hibernate.STRING)
                        .addScalar("id", Hibernate.LONG);
                qry.setCacheable(true);

                qry.setParameterList("ids", ids);
                List<Object[]> zipCodes = (List<Object[]>) qry.list();

                if (zipCodes.size() > 0) {
                    idToZipCodesMap = new HashMap<Long, Set<String>>();
                    for (Object[] zipCode : zipCodes) {
                        Long idFromZipcode = (Long) zipCode[1];
                        Set<String> zipCodesFromMap = idToZipCodesMap.get(idFromZipcode);
                        if (zipCodesFromMap == null) {
                            Set<String> zipCodesToAdd = new HashSet<String>();
                            idToZipCodesMap.put(idFromZipcode, zipCodesToAdd);
                            zipCodesFromMap = zipCodesToAdd;
                        }
                        zipCodesFromMap.add((String) zipCode[0]);
                    }
                }
            }
            List<GisFeatureDistance> results = ResultTransformerUtil.transformToGisFeatureDistance(aliasList,
                    queryResults, idToZipCodesMap, requiredClass);
            return results;
        }
    });

}

From source file:com.gisgraphy.domain.repository.OpenStreetMapDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<StreetDistance> getNearestAndDistanceFrom(final Point point, final double distance,
        final int firstResult, final int maxResults, final StreetType streetType, final Boolean oneWay,
        final String name, final StreetSearchMode streetSearchMode, final boolean includeDistanceField) {
    if (streetSearchMode == StreetSearchMode.FULLTEXT && !GisgraphyConfig.STREET_SEARCH_FULLTEXT_MODE) {
        throw new GisgraphyException(
                "The fulltext mode has been removed in gisgraphy v 3.0 and has been replaced by fulltext webservice with placetype=street. please Consult user guide.");
    }//from w  ww.  ja v a2s . c  o  m
    if (name != null && streetSearchMode == null) {
        throw new IllegalArgumentException("streetSearchmode can not be null if name is provided");
    }
    if (point == null && streetSearchMode == StreetSearchMode.CONTAINS) {
        throw new IllegalArgumentException(
                "you must specify lat/lng when streetsearchmode = " + StreetSearchMode.CONTAINS);
    }
    return (List<StreetDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(OpenStreetMap.class);

            List<String> fieldList = IntrospectionHelper.getFieldsAsList(OpenStreetMap.class);

            ProjectionList projections = ProjectionBean.fieldList(fieldList, false);
            if (includeDistanceField && point != null) {
                projections.add(
                        //            SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME).as(
                        //               "distance"));
                        SpatialProjection.distance_pointToLine(point, OpenStreetMap.SHAPE_COLUMN_NAME)
                                .as("distance"));
            }
            criteria.setProjection(projections);
            if (includeDistanceField && point != null) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            if (point != null) {
                Polygon polygonBox = GeolocHelper.createPolygonBox(point.getX(), point.getY(), distance);
                criteria = criteria.add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME, polygonBox));
            }
            if (name != null) {
                if (streetSearchMode == StreetSearchMode.CONTAINS) {
                    criteria = criteria.add(Restrictions.isNotNull("name"));//optimisation!
                    criteria = criteria.add(
                            Restrictions.ilike(OpenStreetMap.FULLTEXTSEARCH_PROPERTY_NAME, "%" + name + "%"));
                    //criteria = criteria.add(new PartialWordSearchRestriction(OpenStreetMap.PARTIALSEARCH_VECTOR_COLUMN_NAME, name));
                } else if (streetSearchMode == StreetSearchMode.FULLTEXT) {
                    criteria = criteria.add(
                            new FulltextRestriction(OpenStreetMap.FULLTEXTSEARCH_VECTOR_PROPERTY_NAME, name));
                } else {
                    throw new NotImplementedException(
                            streetSearchMode + " is not implemented for street search");
                }
            }
            if (streetType != null) {
                criteria = criteria.add(Restrictions.eq("streetType", streetType));
            }
            if (oneWay != null) {
                criteria = criteria.add(Restrictions.eq("oneWay", oneWay));
            }
            criteria.setCacheable(true);
            // List<Object[]> queryResults =testCriteria.list();
            List<?> queryResults = criteria.list();

            if (queryResults != null && queryResults.size() != 0) {
                String[] propertiesNameArray;
                if (includeDistanceField && point != null) {
                    propertiesNameArray = (String[]) ArrayUtils
                            .add(IntrospectionHelper.getFieldsAsArray(OpenStreetMap.class), "distance");
                } else {
                    propertiesNameArray = IntrospectionHelper.getFieldsAsArray(OpenStreetMap.class);
                }
                List<StreetDistance> results = ResultTransformerUtil
                        .transformToStreetDistance(propertiesNameArray, queryResults);
                return results;
            } else {
                return new ArrayList<StreetDistance>();
            }

        }
    });
}