Example usage for org.hibernate Criteria scroll

List of usage examples for org.hibernate Criteria scroll

Introduction

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

Prototype

public ScrollableResults scroll() throws HibernateException;

Source Link

Document

Get the results as an instance of ScrollableResults .

Usage

From source file:net.firejack.platform.core.store.AbstractStore.java

License:Apache License

@Override
@Transactional(readOnly = true)//from   w w  w . j a va  2 s . co  m
public int count(final List<Criterion> criterions, final Map<String, String> aliases,
        final SpecifiedIdsFilter filter) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        @Override
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = createCriteriaForFilter(session, filter);

            if (aliases != null && !aliases.isEmpty()) {
                for (Map.Entry<String, String> alias : aliases.entrySet()) {
                    criteria.createAlias(alias.getKey(), alias.getValue());
                }
            }

            if (criterions != null && !criterions.isEmpty()) {
                for (Criterion restrictions : criterions) {
                    criteria.add(restrictions);
                }
            }

            ScrollableResults scroll = criteria.scroll();
            return scroll.last() ? scroll.getRowNumber() + 1 : 0;
        }
    });
}

From source file:net.firejack.platform.core.store.BaseStore.java

License:Apache License

public Integer findCountWithFilter(final List<Criterion> criterions, final Map<String, String> aliases,
        final SpecifiedIdsFilter filter, final Projection projection) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = createCriteriaForFilter(session, filter);

            if (aliases != null && !aliases.isEmpty()) {
                for (Map.Entry<String, String> alias : aliases.entrySet()) {
                    criteria.createAlias(alias.getKey(), alias.getValue(), CriteriaSpecification.LEFT_JOIN);
                }/*from w  ww  . j av  a 2s  .c  om*/
            }

            if (criterions != null && !criterions.isEmpty()) {
                for (Criterion restrictions : criterions) {
                    criteria.add(restrictions);
                }
            }

            if (projection != null) {
                criteria.setProjection(projection);
            }

            ScrollableResults scroll = criteria.scroll();
            return scroll.last() ? scroll.getRowNumber() + 1 : 0;
        }
    });
}

From source file:org.codehaus.grepo.query.hibernate.executor.ScrollQueryExecutor.java

License:Apache License

/**
 * {@inheritDoc}/* w w w  . ja va 2  s  . c  om*/
 */
public Object execute(QueryMethodParameterInfo qmpi, HibernateQueryExecutionContext context) {
    HibernateQueryOptions queryOptions = qmpi.getMethodAnnotation(HibernateQueryOptions.class);
    ScrollMode scrollMode = getScrollMode(qmpi, queryOptions);

    Criteria criteria = createCriteria(qmpi, context);
    if (criteria == null) {
        Query query = createQuery(qmpi, context);
        if (scrollMode == null) {
            return query.scroll();
        }
        return query.scroll(scrollMode);
    }
    if (scrollMode == null) {
        return criteria.scroll();
    }
    return criteria.scroll(scrollMode);
}

From source file:org.eurocarbdb.action.core.SearchGlycanSequence.java

License:Open Source License

public List<GlycanSequence> getQueryResults() {
    Criteria query = createCriteria();

    log.info("Performing query: " + query.toString());
    setMessage(query.toString());/*  www.  ja  v a2  s  . c o  m*/

    ScrollableResults scroll = null;
    try {

        scroll = query.scroll();

        scroll.last();
        setTotalResults(scroll.getRowNumber() + 1);

        int count = getTotalResults();

        int first = getOffset();
        int max = getMaxResults();

        if (first > 0) {
            query.setFirstResult(first);
        }

        if (max > 0) {
            query.setMaxResults(max);
        }

        List<GlycanSequence> ret = (List<GlycanSequence>) query.list();

        log.debug("query executed ok, results count=" + ret.size());
        return ret;
    } catch (HibernateException e) {
        log.warn("Caught " + e.getClass().getName() + " performing query:", e);

        return Collections.emptyList();
    } finally {
        if (scroll != null)
            scroll.close();
    }
}

From source file:org.geomajas.layer.hibernate.HibernateLayer.java

License:Open Source License

/**
 * This implementation does not support the 'offset' parameter. The maxResultSize parameter is not used (limiting
 * the result needs to be done after security {@link org.geomajas.internal.layer.vector.GetFeaturesEachStep}). If
 * you expect large results to be returned enable scrollableResultSet to retrieve only as many records as needed.
 *///from w w  w.ja  va 2s .co m
public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {
    try {
        Session session = getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());
        if (filter != null) {
            if (filter != Filter.INCLUDE) {
                CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) featureModel, dateFormat);
                Criterion c = (Criterion) filter.accept(visitor, criteria);
                if (c != null) {
                    criteria.add(c);
                }
            }
        }

        // Sorting of elements.
        if (getFeatureInfo().getSortAttributeName() != null) {
            if (SortType.ASC.equals(getFeatureInfo().getSortType())) {
                criteria.addOrder(Order.asc(getFeatureInfo().getSortAttributeName()));
            } else {
                criteria.addOrder(Order.desc(getFeatureInfo().getSortAttributeName()));
            }
        }

        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        if (isScrollableResultSet()) {
            return (Iterator<?>) new ScrollIterator(criteria.scroll());
        } else {
            List<?> list = criteria.list();
            return list.iterator();
        }
    } catch (HibernateException he) {
        throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL,
                getFeatureInfo().getDataSourceName(), filter.toString());
    }
}

From source file:org.n52.sos.ds.hibernate.dao.i18n.AbstractHibernateI18NDAO.java

License:Open Source License

protected void deleteOldValues(String id, Session session) {
    Criteria criteria = session.createCriteria(getHibernateEntityClass());
    criteria.createCriteria(AbstractHibernateI18NMetadata.OBJECT_ID)
            .add(Restrictions.eq(AbstractIdentifierNameDescriptionEntity.IDENTIFIER, id));
    ScrollableResults scroll = null;/*w w w .  j av a 2 s  . co  m*/
    try {
        scroll = criteria.scroll();
        while (scroll.next()) {
            @SuppressWarnings("unchecked")
            H h18n = (H) scroll.get()[0];
            session.delete(h18n);
        }
    } finally {
        if (scroll != null) {
            scroll.close();
        }
    }
    session.flush();
}

From source file:org.n52.sos.ds.hibernate.util.ScrollableIterable.java

License:Open Source License

public static <T> ScrollableIterable<T> fromCriteria(Criteria c) {
    return new ScrollableIterable<T>(c.scroll());
}

From source file:vn.vnpttech.ssdc.nms.dao.hibernate.DeviceDaoHibernate.java

License:Apache License

@Override
public Map searchDevice(String deviceMAC, String deviceSerialNumber, String deviceStatus,
        String deviceFirmwareStatus, String deviceModel, String deviceFirmware, String deviceProvince,
        String deviceDistrict, List<Area> listArea, String ipAddress, String username, Long start, Long limit) {
    try {//from w w  w  .j a v a 2s  . c  o  m
        int total = 0;
        Map pagingMap = new HashMap();

        List<Device> listDevice = new ArrayList<Device>();
        Criteria criteria = getSession().createCriteria(Device.class);
        //MAC
        if (StringUtils.isNotBlank(deviceMAC)) {
            criteria.add(Restrictions.like("mac", deviceMAC.trim(), MatchMode.ANYWHERE).ignoreCase());
        }
        //Serial Number
        if (StringUtils.isNotBlank(deviceSerialNumber)) {
            criteria.add(Restrictions.like("serialNumber", "%" + deviceSerialNumber.trim() + "%").ignoreCase());
        }
        //Device status
        if (StringUtils.isNotBlank(deviceStatus)) {
            criteria.add(Restrictions.eq("cpeStatus", Integer.parseInt(deviceStatus.trim())));
        }
        //Firmware Status
        if (StringUtils.isNotBlank(deviceFirmwareStatus)) {
            criteria.add(Restrictions.eq("firmwareStatus", Integer.parseInt(deviceFirmwareStatus.trim())));
        }
        //Model
        if (StringUtils.isNotBlank(deviceModel)) {
            criteria.add(Restrictions.eq("deviceModel.id", Long.parseLong(deviceModel.trim())));
        }
        //Firmware
        if (StringUtils.isNotBlank(deviceFirmware)) {
            criteria.add(Restrictions.eq("firmwareVersion", deviceFirmware.trim()).ignoreCase());
        }

        //IP
        if (StringUtils.isNotBlank(ipAddress)) {
            criteria.add(Restrictions.like("ipAddress", ipAddress.trim(), MatchMode.ANYWHERE).ignoreCase());
        }
        // username 
        if (StringUtils.isNotBlank(username)) {
            criteria.add(Restrictions.like("stbUsername", username.trim(), MatchMode.ANYWHERE).ignoreCase());
        }

        //Province
        if (!listArea.isEmpty()) {
            criteria.add(Restrictions.in("area", listArea));
        }
        //            if (StringUtils.isNotBlank(deviceProvince)) {
        //                //District
        //                if (StringUtils.isBlank(deviceDistrict)) { //province level
        //                    criteria.createCriteria("area").add(Restrictions.eq("area.id", Long.parseLong(deviceProvince.trim())));
        //                } else {//district level
        //                    criteria.add(Restrictions.eq("area.id", Long.parseLong(deviceDistrict.trim())));
        //                }
        //            }
        criteria.addOrder(Order.desc("id"));
        //Paging
        if (limit != null && limit > 0) {
            // get the count
            ScrollableResults results = criteria.scroll();
            results.last();
            total = results.getRowNumber() + 1;
            results.close();
            //End get count
            criteria.setFirstResult(start.intValue());
            criteria.setMaxResults(limit.intValue());
        }

        listDevice = criteria.list();
        pagingMap.put("list", listDevice);
        pagingMap.put("totalCount", Long.parseLong(String.valueOf(total)));
        return pagingMap;
    } catch (Exception ex) {
        log.error("ERROR searchDevice: ", ex);
        return null;
    }
}

From source file:vn.vnpttech.ssdc.nms.dao.hibernate.PolicyDaoHibernate.java

License:Apache License

@Override
public Map searchPolicy(String policyName, String policyStatus, String enable, String startTime, String endTime,
        Long start, Long limit) {
    try {/*from  w  ww  . j av a 2s  .  c o m*/

        int total = 0;
        Map pagingMap = new HashMap();

        List<Policy> listPolicy = new ArrayList<Policy>();
        Criteria criteria = getSession().createCriteria(Policy.class);
        //Name
        if (StringUtils.isNotBlank(policyName)) {
            criteria.add(Restrictions.like("name", "%" + policyName.trim() + "%").ignoreCase());
        }
        //Status
        if (StringUtils.isNotBlank(policyStatus)) {
            criteria.add(Restrictions.eq("policyStatus", Integer.parseInt(policyStatus.trim())));
        }
        //Enable
        if (StringUtils.isNotBlank(enable)) {
            criteria.add(Restrictions.eq("enable", Integer.parseInt(enable.trim())));
        }
        //Start Time & End Time
        if (StringUtils.isNotBlank(startTime)) {
            Date startTimeInDate = sdf.parse(startTime);
            criteria.add(Restrictions.ge("startTime", startTimeInDate));

        }
        if (StringUtils.isNotBlank(endTime)) {
            Date endTimeInDate = sdf.parse(endTime);
            criteria.add(Restrictions.le("endTime", endTimeInDate));
        }
        criteria.addOrder(Order.desc("id"));
        //Paging
        if (limit != null && limit > 0) {
            // get the count
            ScrollableResults results = criteria.scroll();
            results.last();
            total = results.getRowNumber() + 1;
            results.close();
            //End get count
            criteria.setFirstResult(start.intValue());
            criteria.setMaxResults(limit.intValue());
        }

        listPolicy = criteria.list();
        pagingMap.put("list", listPolicy);
        pagingMap.put("totalCount", Long.parseLong(String.valueOf(total)));
        return pagingMap;
    } catch (Exception ex) {
        log.error("ERROR searchPolicy: ", ex);
        return null;
    }
}

From source file:vn.vnpttech.ssdc.nms.dao.hibernate.PolicyHistoryDaoHibernate.java

License:Apache License

@Override
public Map searchPolicyHistory(String policyId, String deviceId, Long start, Long limit) {
    try {/*  w w w.j  ava 2s  . co m*/
        int total = 0;
        Map pagingMap = new HashMap();

        List<PolicyHistory> listPolicyHistory = new ArrayList<>();
        Criteria criteria = getSession().createCriteria(PolicyHistory.class);
        //Policy
        if (StringUtils.isNotBlank(policyId)) {
            criteria.add(Restrictions.eq("policy.id", Long.parseLong(policyId.trim())));
        }
        //Device
        if (StringUtils.isNotBlank(deviceId)) {
            criteria.add(Restrictions.eq("device.id", Long.parseLong(deviceId.trim())));
        }

        criteria.addOrder(Order.desc("id"));
        //Paging
        if (limit != null && limit > 0) {
            // get the count
            ScrollableResults results = criteria.scroll();
            results.last();
            total = results.getRowNumber() + 1;
            results.close();
            //End get count
            criteria.setFirstResult(start.intValue());
            criteria.setMaxResults(limit.intValue());
        }

        listPolicyHistory = criteria.list();
        pagingMap.put("list", listPolicyHistory);
        pagingMap.put("totalCount", Long.parseLong(String.valueOf(total)));
        return pagingMap;
    } catch (Exception ex) {
        log.error("ERROR searchPolicyHistory: ", ex);
        return null;
    }
}