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:com.gisgraphy.domain.repository.OpenStreetMapDao.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public OpenStreetMap getNearestByosmIds(final Point point, final List<Long> ids) {
    if (ids == null || ids.size() == 0) {
        return null;
    }/*from  www .  jav a  2  s  .co m*/
    return (OpenStreetMap) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria criteria = session.createCriteria(OpenStreetMap.class);

            criteria.add(new DistanceRestriction(point, DEFAULT_DISTANCE, true));
            criteria.add(Restrictions.in("openstreetmapId", ids));

            String pointAsString = "ST_GeometryFromText('POINT(" + point.getX() + " " + point.getY() + ")',"
                    + SRID.WGS84_SRID.getSRID() + ")";
            String distanceCondition = new StringBuffer().append(DISTANCE_SPHERE_FUNCTION).append("(")
                    .append(pointAsString).append(",").append(SpatialProjection.ST_CLOSEST_POINT).append("(")
                    .append("this_.").append(OpenStreetMap.SHAPE_COLUMN_NAME).append(",").append(pointAsString)
                    .append(")").append(")").toString();
            criteria.addOrder(new NativeSQLOrder(distanceCondition));
            criteria = criteria.setMaxResults(1);
            criteria.setCacheable(true);
            // List<Object[]> queryResults =testCriteria.list();
            OpenStreetMap openStreetMap = (OpenStreetMap) criteria.uniqueResult();

            return openStreetMap;

        }
    });
}

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

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public OpenStreetMap getNearestFrom(final Point point, final boolean onlyroad, final boolean filterEmptyName) {
    if (point == null) {
        return null;
    }/*from  w  ww.j av a 2s. c om*/
    return (OpenStreetMap) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria criteria = session.createCriteria(OpenStreetMap.class);

            if (point != null) {
                //An intersect restriction will probably have better performances and use the index than a distance restriction 
                Polygon polygonBox = GeolocHelper.createPolygonBox(point.getX(), point.getY(),
                        DEFAULT_DISTANCE);
                criteria = criteria.add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME, polygonBox));
            }
            if (onlyroad) {
                criteria = criteria.add(Restrictions.ne("streetType", StreetType.FOOTWAY));
            }
            if (filterEmptyName) {
                criteria = criteria.add(Restrictions.isNotNull("name"));
            }

            String pointAsString = "ST_GeometryFromText('POINT(" + point.getX() + " " + point.getY() + ")',"
                    + SRID.WGS84_SRID.getSRID() + ")";
            String distanceCondition = new StringBuffer().append(DISTANCE_SPHERE_FUNCTION).append("(")
                    .append(pointAsString).append(",").append(SpatialProjection.ST_CLOSEST_POINT).append("(")
                    .append("this_.").append(OpenStreetMap.SHAPE_COLUMN_NAME).append(",").append(pointAsString)
                    .append(")").append(")").toString();
            criteria.addOrder(new NativeSQLOrder(distanceCondition));
            criteria = criteria.setMaxResults(1);
            criteria.setCacheable(true);
            // List<Object[]> queryResults =testCriteria.list();
            OpenStreetMap openStreetMap = (OpenStreetMap) criteria.uniqueResult();

            return openStreetMap;

        }
    });
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query./*  www . j  a  va  2  s.  c  o m*/
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.hmsinc.epicenter.model.surveillance.impl.SurveillanceRepositoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Anomaly> getAnomalies(final DateTime startDate, final DateTime endDate, final boolean includeAll,
        final Geometry filter, final Geometry excludeFacilityEventsFilter, Integer offset, Integer numRows) {

    final Criteria c = criteriaQuery(entityManager, Anomaly.class);
    c.setCacheable(true);

    applyAnomalyCriteria(c, startDate, endDate, includeAll, filter, excludeFacilityEventsFilter);

    if (offset != null) {
        c.setFirstResult(offset);//from   w  w  w  . j a v  a  2 s .  co  m
    }
    if (numRows != null) {
        c.setMaxResults(numRows);
    }

    return c.addOrder(Order.desc("analysisTimestamp")).list();

}

From source file:com.hmsinc.epicenter.model.surveillance.impl.SurveillanceRepositoryImpl.java

License:Open Source License

public Integer getAnomalyCount(final DateTime startDate, final DateTime endDate, final boolean includeAll,
        final Geometry filter, final Geometry excludeFacilityEventsFilter) {

    final Criteria c = criteriaQuery(entityManager, Anomaly.class);
    c.setCacheable(true);

    applyAnomalyCriteria(c, startDate, endDate, includeAll, filter, excludeFacilityEventsFilter);

    return (Integer) c.setProjection(Projections.rowCount()).uniqueResult();
}

From source file:com.hmsinc.epicenter.model.surveillance.impl.SurveillanceRepositoryImpl.java

License:Open Source License

public Anomaly getLatestAnomaly(final Geography geography, final Classification classification,
        final SurveillanceTask task, final SurveillanceMethod method, final SurveillanceSet set,
        final DateTime maxTime) {

    final Criteria c = criteriaQuery(entityManager, Anomaly.class);
    c.add(Restrictions.eq("geography", geography));
    if (classification != null) {
        c.add(Restrictions.eq("classification", classification));
    }//from  w ww  .j  a va2  s  .co  m

    if (task != null) {
        c.add(Restrictions.eq("task", task));
    }

    if (method != null) {
        c.add(Restrictions.eq("method", method));
    }

    if (set != null) {
        c.add(Restrictions.eq("set", set));
    }

    if (maxTime != null) {
        c.add(Restrictions.le("analysisTimestamp", maxTime));
    }

    c.setCacheable(false);
    c.addOrder(Order.desc("analysisTimestamp"));
    c.setMaxResults(1);

    final Anomaly anomaly = (Anomaly) c.uniqueResult();
    return anomaly;
}

From source file:com.jdon.persistence.hibernate.HibernateTemplate.java

License:Apache License

/**
 * Prepare the given Criteria object, applying cache settings and/or a
 * transaction timeout./*  w w  w .ja  v a2  s .  c o m*/
 * 
 * @param criteria
 *            the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 * @see SessionProviderHolder#applyTransactionTimeout
 */
protected void prepareCriteria(Criteria criteria) {
    if (isCacheQueries()) {
        criteria.setCacheable(true);
        if (getQueryCacheRegion() != null) {
            criteria.setCacheRegion(getQueryCacheRegion());
        }
    }
    if (getFetchSize() > 0) {
        criteria.setFetchSize(getFetchSize());
    }
    if (getMaxResults() > 0) {
        criteria.setMaxResults(getMaxResults());
    }
}

From source file:com.lighting.platform.base.dao.SimpleHibernateDao.java

License:Apache License

/**
 * Criteriadistinct transformer./*from www. j a  va 2 s. c  o m*/
 * ?HQL??, ?distinct?.
 */
public Criteria distinct(Criteria criteria) {
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return criteria.setCacheable(cacheable());
}

From source file:com.lighting.platform.base.dao.SimpleHibernateDao.java

License:Apache License

/**
 * ?Criterion?Criteria.//w w w.j  a  va 2 s . c  o  m
 * find()???.
 * 
 * @param criterions ???Criterion.
 */
public Criteria createCriteria(final Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(entityClass);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    return criteria.setCacheable(cacheable());
}

From source file:com.mercatis.lighthouse3.persistence.environment.hibernate.DeploymentRegistryImplementation.java

License:Apache License

@Override
protected Criteria entityToCriteria(Session session, Deployment entityTemplate) {

    Criteria criteria = super.entityToCriteria(session, entityTemplate);

    if (entityTemplate.getDeployedComponent() != null)
        criteria.add(Restrictions.eq("deployedComponent", entityTemplate.getDeployedComponent()));

    if (entityTemplate.getLocation() != null)
        criteria.add(Restrictions.eq("location", entityTemplate.getLocation()));

    if (entityTemplate.getDescription() != null)
        criteria.add(Restrictions.eq("description", entityTemplate.getDescription()));

    if (entityTemplate.getContact() != null)
        criteria.add(Restrictions.eq("contact", entityTemplate.getContact()));

    if (entityTemplate.getContactEmail() != null)
        criteria.add(Restrictions.eq("contactEmail", entityTemplate.getContactEmail()));

    criteria.setCacheable(true);

    return criteria;
}