Example usage for org.hibernate.criterion Restrictions like

List of usage examples for org.hibernate.criterion Restrictions like

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions like.

Prototype

public static SimpleExpression like(String propertyName, String value, MatchMode matchMode) 

Source Link

Document

Apply a "like" constraint to the named property using the provided match mode

Usage

From source file:com.eryansky.common.orm.core.hibernate.restriction.support.LikeRestriction.java

License:Apache License

public Criterion build(String propertyName, Object value) {
    return Restrictions.like(propertyName, value.toString(), MatchMode.ANYWHERE);
}

From source file:com.eryansky.common.orm.core.hibernate.restriction.support.LLikeRestriction.java

License:Apache License

public Criterion build(String propertyName, Object value) {

    return Restrictions.like(propertyName, value.toString(), MatchMode.END);
}

From source file:com.eryansky.common.orm.core.hibernate.restriction.support.RLikeRestriction.java

License:Apache License

public Criterion build(String propertyName, Object value) {

    return Restrictions.like(propertyName, value.toString(), MatchMode.START);
}

From source file:com.eryansky.modules.sys.web.OrganController.java

License:Apache License

/**
 * combogrid/*w w  w.j  a v a 2  s. c  o m*/
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "combogrid" })
@ResponseBody
public Datagrid<Organ> combogrid(String nameOrCode,
        @RequestParam(value = "ids", required = false) List<Long> ids, Integer rows) throws Exception {
    Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
    Criterion[] criterions = new Criterion[0];
    criterions = ArrayUtils.add(criterions, 0, statusCriterion);
    Criterion criterion = null;
    if (Collections3.isNotEmpty(ids)) {
        //in?
        Criterion inCriterion = Restrictions.in("id", ids);

        if (StringUtils.isNotBlank(nameOrCode)) {
            Criterion nameCriterion = Restrictions.like("name", nameOrCode, MatchMode.ANYWHERE);
            Criterion codeCriterion = Restrictions.like("code", nameOrCode, MatchMode.ANYWHERE);
            Criterion criterion1 = Restrictions.or(nameCriterion, codeCriterion);
            criterion = Restrictions.or(inCriterion, criterion1);
        } else {
            criterion = inCriterion;
        }
        //??
        criterions = ArrayUtils.add(criterions, 0, criterion);
    } else {
        if (StringUtils.isNotBlank(nameOrCode)) {
            Criterion nameCriterion = Restrictions.like("name", nameOrCode, MatchMode.ANYWHERE);
            Criterion codeCriterion = Restrictions.like("code", nameOrCode, MatchMode.ANYWHERE);
            criterion = Restrictions.or(nameCriterion, codeCriterion);
            //??
            criterions = ArrayUtils.add(criterions, 0, criterion);
        }
    }

    //
    Page<Organ> p = new Page<Organ>(rows);//
    p = organManager.findPageByCriteria(p, criterions);
    Datagrid<Organ> dg = new Datagrid<Organ>(p.getTotalCount(), p.getResult());
    return dg;
}

From source file:com.eryansky.web.base.OrganAction.java

License:Apache License

/**
 * combogrid//from   ww  w. j a  v a  2 s  .  c o  m
 * @return
 * @throws Exception
 */
public String combogrid() throws Exception {
    try {
        Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
        Criterion[] criterions = new Criterion[0];
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
        Criterion criterion = null;
        if (!Collections3.isEmpty(ids)) {
            //in?
            Criterion inCriterion = Restrictions.in("id", ids);

            if (StringUtils.isNotBlank(nameOrCode)) {
                Criterion nameCriterion = Restrictions.like("name", nameOrCode, MatchMode.ANYWHERE);
                Criterion codeCriterion = Restrictions.like("code", nameOrCode, MatchMode.ANYWHERE);
                Criterion criterion1 = Restrictions.or(nameCriterion, codeCriterion);
                criterion = Restrictions.or(inCriterion, criterion1);
            } else {
                criterion = inCriterion;
            }
            //??
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
        } else {
            if (StringUtils.isNotBlank(nameOrCode)) {
                Criterion nameCriterion = Restrictions.like("name", nameOrCode, MatchMode.ANYWHERE);
                Criterion codeCriterion = Restrictions.like("code", nameOrCode, MatchMode.ANYWHERE);
                criterion = Restrictions.or(nameCriterion, codeCriterion);
                //??
                criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
            }
        }

        //
        Page<Organ> p = new Page<Organ>(rows);//
        p = organManager.findByCriteria(p, criterions);
        Datagrid<Organ> dg = new Datagrid<Organ>(p.getTotalCount(), p.getResult());
        Struts2Utils.renderJson(dg);
    } catch (Exception e) {
        throw e;
    }
    return null;
}

From source file:com.eryansky.web.base.UserAction.java

License:Apache License

/**
 * combogrid/*from  ww w  .  j  a  va 2 s  . c  o m*/
 * @return
 * @throws Exception
 */
public String combogrid() throws Exception {
    try {
        Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
        Criterion[] criterions = new Criterion[0];
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
        Criterion criterion = null;
        if (!Collections3.isEmpty(ids)) {
            //in?
            Criterion inCriterion = Restrictions.in("id", ids);

            if (StringUtils.isNotBlank(loginNameOrName)) {
                Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName,
                        MatchMode.ANYWHERE);
                Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
                Criterion criterion1 = Restrictions.or(loginNameCriterion, nameCriterion);
                criterion = Restrictions.or(inCriterion, criterion1);
            } else {
                criterion = inCriterion;
            }
            //??
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
        } else {
            if (StringUtils.isNotBlank(loginNameOrName)) {
                Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName,
                        MatchMode.ANYWHERE);
                Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
                criterion = Restrictions.or(loginNameCriterion, nameCriterion);
                //??
                criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
            }
        }

        //
        Page<User> p = new Page<User>(rows);//
        p = userManager.findByCriteria(p, criterions);
        Datagrid<User> dg = new Datagrid<User>(p.getTotalCount(), p.getResult());
        Struts2Utils.renderJson(dg);
    } catch (Exception e) {
        throw e;
    }
    return null;
}

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.ja  v a 2 s. co  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.DbObjectMetadataManagerImpl.java

License:Open Source License

@Override
public List<ObjectEntity> lookupObjectsForReaping(Bucket bucket, String objectKeyPrefix, Date age) {
    List<ObjectEntity> results;
    try (TransactionResource tran = Entities.transactionFor(ObjectEntity.class)) {
        // setup example and criteria
        ObjectEntity example = new ObjectEntity().withState(ObjectState.extant).withBucket(bucket);
        Criteria search = Entities.createCriteria(ObjectEntity.class).add(Example.create(example));
        search.add(Restrictions.and(Restrictions.like("objectKey", objectKeyPrefix, MatchMode.START),
                Restrictions.lt("creationTimestamp", age)));
        search = getSearchByBucket(search, bucket);
        results = search.list();/*from  ww w  .j  a v  a  2 s .  c  om*/
        tran.commit();
    } catch (Exception ex) {
        LOG.error("exception caught while retrieving objects prefix with " + objectKeyPrefix + " from bucket "
                + bucket.getBucketName() + ", error message - " + ex.getMessage());
        return Collections.EMPTY_LIST;
    }
    return results;
}

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 = "";
            }/* w  ww  .  j av  a2 s.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 {//from  w ww  .j  av a2s  .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();
    }
}