Example usage for org.hibernate Criteria setFetchSize

List of usage examples for org.hibernate Criteria setFetchSize

Introduction

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

Prototype

public Criteria setFetchSize(int fetchSize);

Source Link

Document

Set a fetch size for the underlying JDBC query.

Usage

From source file:abid.password.swing.dao.hibernate.AbstractHibernateDao.java

License:Apache License

@SuppressWarnings("unchecked")
public List<T> get(int first, int fetchSize) {
    Session session = sessionFactory.openSession();
    try {/*from   w  w  w .  j av  a2 s .c o m*/
        Criteria criteria = session.createCriteria(persistentClass);
        criteria.setFirstResult(first);
        criteria.setMaxResults(fetchSize);
        criteria.setFetchSize(fetchSize);
        criteria.setCacheable(true);

        List<T> dataList = (List<T>) criteria.list();
        return dataList;
    } finally {
        session.close();
    }
}

From source file:abid.password.swing.dao.hibernate.AbstractHibernateDao.java

License:Apache License

@SuppressWarnings("unchecked")
public List<T> getSorted(int first, int fetchSize, String propertyName, boolean ascending) {
    Session session = sessionFactory.openSession();
    try {/*from   w w w.  java  2s. c  o  m*/
        Criteria criteria = session.createCriteria(persistentClass);
        criteria.setFirstResult(first);
        criteria.setMaxResults(fetchSize);
        criteria.setFetchSize(fetchSize);
        criteria.setCacheable(true);

        if (ascending) {
            criteria.addOrder(Order.asc(propertyName));
        } else {
            criteria.addOrder(Order.desc(propertyName));
        }

        List<T> dataList = (List<T>) criteria.list();
        return dataList;
    } finally {
        session.close();
    }
}

From source file:abid.password.wicket.dao.AbstractHibernateDao.java

License:Apache License

@Transactional(type = TransactionType.READ_ONLY)
@SuppressWarnings("unchecked")
public List<T> get(int first, int fetchSize) {
    Criteria criteria = session.get().createCriteria(persistentClass);
    criteria.setFirstResult(first);/*from  www . ja v  a  2s  . c om*/
    criteria.setMaxResults(fetchSize);
    criteria.setFetchSize(fetchSize);
    criteria.setCacheable(true);

    List<T> dataList = (List<T>) criteria.list();
    return dataList;
}

From source file:abid.password.wicket.dao.AbstractHibernateDao.java

License:Apache License

@Transactional(type = TransactionType.READ_ONLY)
@SuppressWarnings("unchecked")
public List<T> getSorted(int first, int fetchSize, String propertyName, boolean ascending) {
    Criteria criteria = session.get().createCriteria(persistentClass);
    criteria.setFirstResult(first);/*from   ww  w  . j  a va2 s .c o m*/
    criteria.setMaxResults(fetchSize);
    criteria.setFetchSize(fetchSize);
    criteria.setCacheable(true);

    if (ascending) {
        criteria.addOrder(Order.asc(propertyName));
    } else {
        criteria.addOrder(Order.desc(propertyName));
    }

    List<T> dataList = (List<T>) criteria.list();
    return dataList;
}

From source file:ch.tatool.app.service.impl.ModuleSessionDAO.java

License:Open Source License

/** Finds the last session for a given module. */
public ModuleSession findLastSession(final ModuleImpl module) {
    return (ModuleSession) getHibernateTemplate().execute(new HibernateCallback() {
        @SuppressWarnings("unchecked")
        public Object doInHibernate(Session session) {
            Criteria criteria = session.createCriteria(ModuleSession.class);
            criteria.add(Restrictions.eq("module", module));
            criteria.setFetchSize(1);
            criteria.addOrder(Order.desc("id"));
            List<ModuleSession> sessions = (List<ModuleSession>) criteria.list();
            if (sessions.size() > 0) {
                return sessions.get(0);
            } else {
                return null;
            }// w  w  w . j  ava2s.  co m
        }
    });
}

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);
    }//from w w  w . ja v  a 2  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.eucalyptus.objectstorage.DbObjectManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<ObjectEntity> listVersionsPaginated(final Bucket bucket, int maxEntries, String prefix,
        String delimiter, String fromKeyMarker, String fromVersionId, boolean latestOnly) throws Exception {

    EntityTransaction db = Entities.get(ObjectEntity.class);
    try {//from w  w  w  .j  a v a  2  s  .  c o  m
        PaginatedResult<ObjectEntity> result = new PaginatedResult<ObjectEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxEntries >= 0) {
            final int queryStrideSize = maxEntries + 1;
            ObjectEntity searchObj = new ObjectEntity();
            searchObj.setBucketName(bucket.getBucketName());

            // Return latest version, so exclude delete markers as well.
            // This makes listVersion act like listObjects
            if (latestOnly) {
                searchObj.setDeleted(false);
                searchObj.setIsLatest(true);
            }

            Criteria objCriteria = Entities.createCriteria(ObjectEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchObj));
            objCriteria.add(ObjectEntity.QueryHelpers.getNotPendingRestriction());
            objCriteria.add(ObjectEntity.QueryHelpers.getNotDeletingRestriction());
            objCriteria.addOrder(Order.asc("objectKey"));
            objCriteria.addOrder(Order.desc("objectModifiedTimestamp"));
            objCriteria.setMaxResults(queryStrideSize);

            if (!Strings.isNullOrEmpty(fromKeyMarker)) {
                objCriteria.add(Restrictions.gt("objectKey", fromKeyMarker));
            } else {
                fromKeyMarker = "";
            }

            if (!Strings.isNullOrEmpty(fromVersionId)) {
                objCriteria.add(Restrictions.gt("versionId", fromVersionId));
            } else {
                fromVersionId = "";
            }

            if (!Strings.isNullOrEmpty(prefix)) {
                objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
            } else {
                prefix = "";
            }

            // Ensure not null.
            if (Strings.isNullOrEmpty(delimiter)) {
                delimiter = "";
            }

            List<ObjectEntity> objectInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            String prefixString = null;
            boolean useDelimiter = !Strings.isNullOrEmpty(delimiter);
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;
                prefixString = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                objectInfos = (List<ObjectEntity>) objCriteria.list();
                if (objectInfos == null) {
                    // nothing to do.
                    break;
                }

                for (ObjectEntity objectRecord : objectInfos) {
                    if (useDelimiter) {
                        // Check if it will get aggregated as a commonprefix
                        parts = objectRecord.getObjectKey().substring(prefix.length()).split(delimiter);
                        if (parts.length > 1) {
                            prefixString = prefix + parts[0] + delimiter;
                            if (!commonPrefixes.contains(prefixString)) {
                                if (resultKeyCount == maxEntries) {
                                    // This is a new record, so we know
                                    // we're truncating if this is true
                                    result.setIsTruncated(true);
                                    resultKeyCount++;
                                    break;
                                } else {
                                    // Add it to the common prefix set
                                    commonPrefixes.add(prefixString);
                                    result.lastEntry = prefixString;
                                    // count the unique commonprefix as a
                                    // single return entry
                                    resultKeyCount++;
                                }
                            } else {
                                // Already have this prefix, so skip
                            }
                            continue;
                        }
                    }

                    if (resultKeyCount == maxEntries) {
                        // This is a new (non-commonprefix) record, so
                        // we know we're truncating
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.entityList.add(objectRecord);
                    result.lastEntry = objectRecord;
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxEntries && objectInfos.size() <= maxEntries) {
                    break;
                }
            } while (resultKeyCount <= maxEntries);

            // Sort the prefixes from the hashtable and add to the reply
            if (commonPrefixes != null) {
                result.getCommonPrefixes().addAll(commonPrefixes);
                Collections.sort(result.getCommonPrefixes());
            }
        } else {
            throw new IllegalArgumentException("MaxKeys must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated object list of bucket " + bucket.getBucketName(), e);
        throw e;
    } finally {
        db.rollback();
    }
}

From source file:com.eucalyptus.objectstorage.metadata.DbMpuPartMetadataManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<PartEntity> listPartsForUpload(final Bucket bucket, final String objectKey,
        final String uploadId, final Integer partNumberMarker, final Integer maxParts) throws Exception {

    EntityTransaction db = Entities.get(PartEntity.class);
    try {/*  w  ww. java 2s .c  om*/
        PaginatedResult<PartEntity> result = new PaginatedResult<PartEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxParts >= 0) {
            final int queryStrideSize = maxParts + 1;
            PartEntity searchPart = new PartEntity(bucket, objectKey, uploadId).withState(ObjectState.extant);

            Criteria objCriteria = Entities.createCriteria(PartEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchPart));
            objCriteria.addOrder(Order.asc("partNumber"));
            objCriteria.addOrder(Order.desc("objectModifiedTimestamp"));
            objCriteria.setMaxResults(queryStrideSize);

            if (partNumberMarker != null) {
                objCriteria.add(Restrictions.gt("partNumber", partNumberMarker));
            }
            objCriteria = getSearchByBucket(objCriteria, bucket);

            List<PartEntity> partInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                partInfos = (List<PartEntity>) objCriteria.list();
                if (partInfos == null) {
                    // nothing to do.
                    break;
                }

                for (PartEntity partRecord : partInfos) {

                    if (resultKeyCount == maxParts) {
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.getEntityList().add(partRecord);
                    result.setLastEntry(partRecord);
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxParts && partInfos.size() <= maxParts) {
                    break;
                }
            } while (resultKeyCount <= maxParts);
        } else {
            throw new IllegalArgumentException("MaxKeys must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated parts list for upload ID " + uploadId, e);
        throw e;
    } finally {
        db.rollback();
    }
}

From source file:com.eucalyptus.objectstorage.metadata.DbObjectMetadataManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<ObjectEntity> listUploads(Bucket bucket, int maxUploads, String prefix, String delimiter,
        String keyMarker, String uploadIdMarker) throws Exception {

    try (TransactionResource trans = Entities.transactionFor(ObjectEntity.class)) {
        PaginatedResult<ObjectEntity> result = new PaginatedResult<ObjectEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxUploads >= 0) {
            final int queryStrideSize = maxUploads + 1;
            ObjectEntity searchObj = new ObjectEntity();
            searchObj.withBucket(bucket); //This doesn't actually filter, but do it anyway
            searchObj.withState(ObjectState.mpu_pending);

            Criteria objCriteria = Entities.createCriteria(ObjectEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchObj));
            objCriteria.addOrder(Order.asc("objectKey"));
            objCriteria.setMaxResults(queryStrideSize);

            if (!Strings.isNullOrEmpty(keyMarker)) {
                objCriteria.add(Restrictions.gt("objectKey", keyMarker));
            } else {
                keyMarker = "";
            }//from w  ww.j  a  v  a 2s. c  om

            if (!Strings.isNullOrEmpty(uploadIdMarker)) {
                objCriteria.add(Restrictions.gt("uploadId", uploadIdMarker));
            } else {
                uploadIdMarker = "";
            }

            if (!Strings.isNullOrEmpty(prefix)) {
                objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
            } else {
                prefix = "";
            }

            //Be sure to add the bucket restriction last
            objCriteria = getSearchByBucket(objCriteria, bucket);

            // Ensure not null.
            if (Strings.isNullOrEmpty(delimiter)) {
                delimiter = "";
            }

            List<ObjectEntity> objectInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            String prefixString = null;
            boolean useDelimiter = !Strings.isNullOrEmpty(delimiter);
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;
                prefixString = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                objectInfos = (List<ObjectEntity>) objCriteria.list();
                if (objectInfos == null) {
                    // nothing to do.
                    break;
                }

                for (ObjectEntity objectRecord : objectInfos) {
                    if (useDelimiter) {
                        // Check if it will get aggregated as a commonprefix
                        parts = objectRecord.getObjectKey().substring(prefix.length()).split(delimiter);
                        if (parts.length > 1) {
                            prefixString = prefix + parts[0] + delimiter;
                            if (!prefixString.equals(keyMarker) && !commonPrefixes.contains(prefixString)) {
                                if (resultKeyCount == maxUploads) {
                                    // This is a new record, so we know
                                    // we're truncating if this is true
                                    result.setIsTruncated(true);
                                    resultKeyCount++;
                                    break;
                                } else {
                                    // Add it to the common prefix set
                                    commonPrefixes.add(prefixString);
                                    result.setLastEntry(prefixString);
                                    // count the unique commonprefix as a
                                    // single return entry
                                    resultKeyCount++;
                                }
                            } else {
                                // Already have this prefix, so skip
                            }
                            continue;
                        }
                    }

                    if (resultKeyCount == maxUploads) {
                        // This is a new (non-commonprefix) record, so
                        // we know we're truncating
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.getEntityList().add(objectRecord);
                    result.setLastEntry(objectRecord);
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxUploads && objectInfos.size() <= maxUploads) {
                    break;
                }
            } while (resultKeyCount <= maxUploads);

            // Sort the prefixes from the hashtable and add to the reply
            if (commonPrefixes != null) {
                result.getCommonPrefixes().addAll(commonPrefixes);
                Collections.sort(result.getCommonPrefixes());
            }
        } else {
            throw new IllegalArgumentException("max uploads must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated multipart upload list for bucket " + bucket.getBucketName(), e);
        throw e;
    }
}

From source file:com.eucalyptus.objectstorage.metadata.DbObjectMetadataManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<ObjectEntity> listVersionsPaginated(final Bucket bucket, int maxEntries, String prefix,
        String delimiter, String fromKeyMarker, String fromVersionId, boolean latestOnly) throws Exception {

    EntityTransaction db = Entities.get(ObjectEntity.class);
    try {//  ww  w .java 2 s.c  om
        PaginatedResult<ObjectEntity> result = new PaginatedResult<ObjectEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxEntries >= 0) {
            final int queryStrideSize = maxEntries + 1;
            ObjectEntity searchObj = new ObjectEntity().withBucket(bucket).withState(ObjectState.extant);

            // Return latest version, so exclude delete markers as well.
            // This makes listVersion act like listObjects
            if (latestOnly) {
                searchObj.setIsLatest(true);
                searchObj.setIsDeleteMarker(false);
            }

            Criteria objCriteria = Entities.createCriteria(ObjectEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchObj));
            objCriteria.addOrder(Order.asc("objectKey"));
            objCriteria.addOrder(Order.desc("objectModifiedTimestamp"));
            objCriteria.setMaxResults(queryStrideSize);

            if (!Strings.isNullOrEmpty(fromKeyMarker)) {
                if (!Strings.isNullOrEmpty(fromVersionId)) {
                    // Look for the key that matches the key-marker and version-id-marker
                    ObjectEntity searchObject = new ObjectEntity(bucket, fromKeyMarker, fromVersionId);
                    ObjectEntity matchingObject = null;
                    try {
                        matchingObject = Entities.uniqueResult(searchObject);
                        if (matchingObject == null || matchingObject.getObjectModifiedTimestamp() == null) {
                            throw new NoSuchKeyException(bucket.getBucketName() + "/" + fromKeyMarker
                                    + "?versionId=" + fromVersionId);
                        }
                    } catch (Exception e) {
                        LOG.warn("No matching object found for key-marker=" + fromKeyMarker
                                + " and version-id-marker=" + fromVersionId);
                        throw new NoSuchKeyException(
                                bucket.getBucketName() + "/" + fromKeyMarker + "?versionId=" + fromVersionId);
                    }

                    // The result set should be exclusive of the key with the key-marker version-id-marker pair. Look for keys that chronologically
                    // follow the version-id-marker for the given key-marker and also the keys that follow the key-marker.
                    objCriteria.add(Restrictions.or(
                            Restrictions.and(Restrictions.eq("objectKey", fromKeyMarker),
                                    Restrictions.lt("objectModifiedTimestamp",
                                            matchingObject.getObjectModifiedTimestamp())),
                            Restrictions.gt("objectKey", fromKeyMarker)));
                } else { // No version-id-marker, just set the criteria the key-marker
                    objCriteria.add(Restrictions.gt("objectKey", fromKeyMarker));
                }
            } else {
                // No criteria to be set
            }

            if (!Strings.isNullOrEmpty(prefix)) {
                objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
            } else {
                prefix = "";
            }

            objCriteria = getSearchByBucket(objCriteria, bucket);

            // Ensure not null.
            if (Strings.isNullOrEmpty(delimiter)) {
                delimiter = "";
            }

            List<ObjectEntity> objectInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            String prefixString = null;
            boolean useDelimiter = !Strings.isNullOrEmpty(delimiter);
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;
                prefixString = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                objectInfos = (List<ObjectEntity>) objCriteria.list();
                if (objectInfos == null) {
                    // nothing to do.
                    break;
                }

                for (ObjectEntity objectRecord : objectInfos) {
                    if (useDelimiter) {
                        // Check if it will get aggregated as a commonprefix
                        parts = objectRecord.getObjectKey().substring(prefix.length()).split(delimiter);
                        if (parts.length > 1) {
                            prefixString = prefix + parts[0] + delimiter;
                            if (!prefixString.equals(fromKeyMarker) && !commonPrefixes.contains(prefixString)) {
                                if (resultKeyCount == maxEntries) {
                                    // This is a new record, so we know
                                    // we're truncating if this is true
                                    result.setIsTruncated(true);
                                    resultKeyCount++;
                                    break;
                                } else {
                                    // Add it to the common prefix set
                                    commonPrefixes.add(prefixString);
                                    result.setLastEntry(prefixString);
                                    // count the unique commonprefix as a
                                    // single return entry
                                    resultKeyCount++;
                                }
                            } else {
                                // Already have this prefix, so skip
                            }
                            continue;
                        }
                    }

                    if (resultKeyCount == maxEntries) {
                        // This is a new (non-commonprefix) record, so
                        // we know we're truncating
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.getEntityList().add(objectRecord);
                    result.setLastEntry(objectRecord);
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxEntries && objectInfos.size() <= maxEntries) {
                    break;
                }
            } while (resultKeyCount <= maxEntries);

            // Sort the prefixes from the hashtable and add to the reply
            if (commonPrefixes != null) {
                result.getCommonPrefixes().addAll(commonPrefixes);
                Collections.sort(result.getCommonPrefixes());
            }
        } else {
            throw new IllegalArgumentException("MaxKeys must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated object list of bucket " + bucket.getBucketName(), e);
        throw e;
    } finally {
        db.rollback();
    }
}