List of usage examples for org.hibernate.criterion DetachedCriteria setProjection
public DetachedCriteria setProjection(Projection projection)
From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java
License:Open Source License
/** * Retrieves an iterator over the compliance snapshots on the target date. * * @param targetDate//from ww w . j a va 2 s . com * The date for which to retrieve compliance snapshots. If null, the current date will be used * instead. * * @param consumerUuids * A list of consumer UUIDs to use to filter the results. If provided, only compliances for * consumers in the list will be retrieved. * * @param ownerFilters * A list of owners to use to filter the results. If provided, only compliances for consumers * belonging to the specified owners (orgs) will be retrieved. * * @param statusFilters * A list of statuses to use to filter the results. If provided, only compliances with a status * matching the list will be retrieved. * * @param productNameFilters * A list of product names to use to filter compliances. If provided, only compliances for * consumers having installed the specified products will be retrieved. * * @param subscriptionSkuFilters * A list of subscription skus to use to filter compliances. If provided, only compliances for * the specified subscription skus will be retrieved. * * @param subscriptionNameFilters * A list of subscription names to use to filter compliances. If provided, only compliances for * the specified subscription names will be retrieved. * * @param attributeFilters * A map of entitlement attributes to use to filter compliances. If provided, only compliances * for entitlements having the specified values for the given attributes will be retrieved. * * @param pageRequest * A PageRequest instance containing paging information from the request. If null, no paging * will be performed. * * @return * A Page instance containing an iterator over the compliance snapshots for the target date and * the paging information for the query. */ @SuppressWarnings("checkstyle:indentation") public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids, List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters, List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters, Map<String, String> attributeFilters, PageRequest pageRequest) { Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>(); page.setPageRequest(pageRequest); DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class); subquery.createAlias("consumer", "c"); subquery.createAlias("c.consumerState", "state"); // https://hibernate.atlassian.net/browse/HHH-2776 if (consumerUuids != null && !consumerUuids.isEmpty()) { subquery.add(Restrictions.in("c.uuid", consumerUuids)); } Date toCheck = targetDate == null ? new Date() : targetDate; subquery.add( Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck))); subquery.add(Restrictions.le("state.created", toCheck)); if (ownerFilters != null && !ownerFilters.isEmpty()) { subquery.createAlias("c.owner", "o"); subquery.add(Restrictions.in("o.key", ownerFilters)); } subquery.add(Restrictions.le("date", toCheck)); subquery.setProjection( Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid"))); Session session = this.currentSession(); Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs") .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery)) .setCacheMode(CacheMode.IGNORE).setReadOnly(true); if ((statusFilters != null && !statusFilters.isEmpty()) || (attributeFilters != null && attributeFilters.containsKey("management_enabled")) || (productNameFilters != null && !productNameFilters.isEmpty())) { query.createAlias("comp.status", "stat"); if (statusFilters != null && !statusFilters.isEmpty()) { query.add(Restrictions.in("stat.status", statusFilters)); } if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) { boolean managementEnabledFilter = PropertyConverter .toBoolean(attributeFilters.get("management_enabled")); query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter)); } if (productNameFilters != null && !productNameFilters.isEmpty()) { query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN) .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN) .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN); DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2"); prodQuery.createAlias("comp2.consumer", "cons2"); prodQuery.createAlias("cons2.installedProducts", "installed"); prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters), Restrictions.eqProperty("comp2.id", "comp.id"))); prodQuery.setProjection(Projections.property("installed.productId")); query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery), Property.forName("pcprod.productId").in(prodQuery), Property.forName("ncprod.productId").in(prodQuery))); } } // Add subscription filters, if necessary if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) { // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy // to errorneously truncate "long" ones. Actual property/field names are safe, though. query.createAlias("comp.entitlements", "entsnap"); if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) { query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters)); } if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) { query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters)); } } if (pageRequest != null && pageRequest.isPaging()) { page.setMaxRecords(this.getRowCount(query)); query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage()); query.setMaxResults(pageRequest.getPerPage()); if (pageRequest.getSortBy() != null) { query.addOrder( pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy()) : Order.desc(pageRequest.getSortBy())); } } page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session, query.scroll(ScrollMode.FORWARD_ONLY), 0)); return page; }
From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java
License:Open Source License
/** * Retrieves an iterator over the compliance snapshots for the specified consumer. * * @param consumerUUID// w ww.j a v a 2 s .co m * The UUID for the consumer for which to retrieve compliance snapshots. * * @param startDate * The start date to use to filter snapshots retrieved. If specified, only snapshots occurring * after the start date, and the snapshot immediately preceding it, will be retrieved. * * @param endDate * The end date to use to filter snapshots retrieved. If specified, only snapshots occurring * before the end date will be retrieved. * * @param pageRequest * A PageRequest instance containing paging information from the request. If null, no paging * will be performed. * * @return * A Page instance containing an iterator over the snapshots for the specified consumer, and * the paging information for the query. */ @SuppressWarnings("checkstyle:indentation") public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate, Date endDate, PageRequest pageRequest) { Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>(); page.setPageRequest(pageRequest); Session session = this.currentSession(); Criteria query = session.createCriteria(Compliance.class, "comp1"); query.createAlias("comp1.consumer", "cons1"); query.add(Restrictions.eq("cons1.uuid", consumerUUID)); if (startDate != null) { DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2"); subquery.createAlias("comp2.consumer", "cons2"); subquery.createAlias("cons2.consumerState", "state2"); subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"), Restrictions.gt("state2.deleted", startDate))); subquery.add(Restrictions.lt("state2.created", startDate)); subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid")); subquery.add(Restrictions.lt("comp2.date", startDate)); subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date"))); query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate)) .add(Subqueries.propertyEq("comp1.date", subquery))); } if (endDate != null) { query.add(Restrictions.le("comp1.date", endDate)); } query.setCacheMode(CacheMode.IGNORE); query.setReadOnly(true); if (pageRequest != null && pageRequest.isPaging()) { page.setMaxRecords(this.getRowCount(query)); query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage()); query.setMaxResults(pageRequest.getPerPage()); if (pageRequest.getSortBy() != null) { query.addOrder( pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy()) : Order.desc(pageRequest.getSortBy())); } } page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session, query.scroll(ScrollMode.FORWARD_ONLY), 0)); return page; }
From source file:org.candlepin.model.PoolFilterBuilder.java
License:Open Source License
private DetachedCriteria createAttributeCriteria(Class<? extends AbstractPoolAttribute> entityClass, String attributeName, List<String> possibleValues) { DetachedCriteria attrMatch = DetachedCriteria.forClass(entityClass, "attr"); attrMatch.add(Restrictions.eq("name", attributeName)); // It would be nice to be able to use an 'in' restriction here, but // hibernate does not support ignoring case with its 'in' restriction. // We could probably roll our own, but would involve duplicating some // hibernate code to achieve it. List<Criterion> attrOrs = new ArrayList<Criterion>(); for (String val : possibleValues) { // Setting an attribute value as '' may end up being set to null, // so we check both. if (val == null || val.isEmpty()) { attrOrs.add(Restrictions.isNull("value")); attrOrs.add(Restrictions.eq("value", "")); } else {//from w ww. j a v a 2s . co m attrOrs.add(Restrictions.eq("value", val).ignoreCase()); } } attrMatch.add(Restrictions.or(attrOrs.toArray(new Criterion[attrOrs.size()]))); attrMatch.add(Property.forName("this.id").eqProperty("attr.pool.id")); attrMatch.setProjection(Projections.property("attr.id")); return attrMatch; }
From source file:org.conventionsframework.dao.impl.BaseHibernateDaoImpl.java
License:Apache License
@Override public Long getRowCount(final DetachedCriteria dc) { Criteria criteria = dc.getExecutableCriteria(getSession()); criteria.setProjection(Projections.rowCount()); criteria.setFirstResult(0);//from w ww . ja v a2s . com criteria.setMaxResults(1); Long result = (Long) criteria.uniqueResult(); dc.setProjection(null).setResultTransformer(Criteria.ROOT_ENTITY); return result; }
From source file:org.dspace.checker.dao.impl.MostRecentChecksumDAOImpl.java
License:BSD License
@Override public List<MostRecentChecksum> findNotInHistory(Context context) throws SQLException { Criteria criteria = createCriteria(context, MostRecentChecksum.class); DetachedCriteria subCriteria = DetachedCriteria.forClass(ChecksumHistory.class); subCriteria.setProjection(Projections.property("bitstream.id")); criteria.add(Property.forName("bitstreamId").notIn(subCriteria)); return list(criteria); }
From source file:org.dspace.content.dao.impl.ItemDAOImpl.java
License:BSD License
@Override public Iterator<Item> findByMetadataQuery(Context context, List<List<MetadataField>> listFieldList, List<String> query_op, List<String> query_val, List<UUID> collectionUuids, String regexClause, int offset, int limit) throws SQLException { Criteria criteria = createCriteria(context, Item.class, "item"); criteria.setFirstResult(offset);/*w ww . j av a 2s . c o m*/ criteria.setMaxResults(limit); if (!collectionUuids.isEmpty()) { DetachedCriteria dcollCriteria = DetachedCriteria.forClass(Collection.class, "coll"); dcollCriteria.setProjection(Projections.property("coll.id")); dcollCriteria.add(Restrictions.eqProperty("coll.id", "item.owningCollection")); dcollCriteria.add(Restrictions.in("coll.id", collectionUuids)); criteria.add(Subqueries.exists(dcollCriteria)); } int index = Math.min(listFieldList.size(), Math.min(query_op.size(), query_val.size())); StringBuilder sb = new StringBuilder(); for (int i = 0; i < index; i++) { OP op = OP.valueOf(query_op.get(i)); if (op == null) { log.warn("Skipping Invalid Operator: " + query_op.get(i)); continue; } if (op == OP.matches || op == OP.doesnt_match) { if (regexClause.isEmpty()) { log.warn("Skipping Unsupported Regex Operator: " + query_op.get(i)); continue; } } DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class, "mv"); subcriteria.add(Property.forName("mv.dSpaceObject").eqProperty("item.id")); subcriteria.setProjection(Projections.property("mv.dSpaceObject")); if (!listFieldList.get(i).isEmpty()) { subcriteria.add(Restrictions.in("metadataField", listFieldList.get(i))); } sb.append(op.name() + " "); if (op == OP.equals || op == OP.not_equals) { subcriteria.add(Property.forName("mv.value").eq(query_val.get(i))); sb.append(query_val.get(i)); } else if (op == OP.like || op == OP.not_like) { subcriteria.add(Property.forName("mv.value").like(query_val.get(i))); sb.append(query_val.get(i)); } else if (op == OP.contains || op == OP.doesnt_contain) { subcriteria.add(Property.forName("mv.value").like("%" + query_val.get(i) + "%")); sb.append(query_val.get(i)); } else if (op == OP.matches || op == OP.doesnt_match) { subcriteria .add(Restrictions.sqlRestriction(regexClause, query_val.get(i), StandardBasicTypes.STRING)); sb.append(query_val.get(i)); } if (op == OP.exists || op == OP.equals || op == OP.like || op == OP.contains || op == OP.matches) { criteria.add(Subqueries.exists(subcriteria)); } else { criteria.add(Subqueries.notExists(subcriteria)); } } log.debug(String.format("Running custom query with %d filters", index)); return list(criteria).iterator(); }
From source file:org.egov.pims.commons.service.PositionService.java
License:Open Source License
/** * gives vacant positions for given date range and designation * @param fromDate/*from w ww . ja va2 s . c o m*/ * @param toDate * @param designationMasterId * @return */ public Criteria getVacantPositionCriteria(Date fromDate, Date toDate, Integer designationMasterId) { DetachedCriteria detachAssignmentPrd = DetachedCriteria.forClass(Assignment.class, "assignment"); detachAssignmentPrd .add(Restrictions.and(Restrictions.le("assignment.fromDate", fromDate), Restrictions.or(Restrictions.ge("assignment.toDate", toDate), Restrictions.isNull("assignment.toDate")))) .setProjection(Projections.property("assignment.id")); DetachedCriteria detachAssignment = DetachedCriteria.forClass(Assignment.class, "assignment"); detachAssignment.add(Subqueries.propertyIn("assignment.id", detachAssignmentPrd)); detachAssignment.add(Restrictions.eq("assignment.isPrimary", 'Y')); detachAssignment.setProjection(Projections.distinct(Projections.property("assignment.position.id"))); Criteria criteria = getCurrentSession().createCriteria(Position.class, "position"); if (designationMasterId != null && !designationMasterId.equals("0")) { criteria.add(Restrictions.eq("position.deptDesig.designation.id", designationMasterId)); } criteria.add(Subqueries.propertyNotIn("position.id", detachAssignment)); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.addOrder(Order.asc("position.name")); return criteria; }
From source file:org.egov.ptis.domain.dao.property.SearchPropertyHibernateDAO.java
License:Open Source License
/** * either objectionNumber or any of the date fields are mandatory * //from ww w. j av a 2 s . co m * @param propertyTypeMasterId * @param objectionNumber * @param fromObjection * @param toObjection * @return * @throws ValidationException * when mandatory fields not passed */ @Override public List<Property> getPropertyByObjectionDetails(Long propertyTypeMasterId, String objectionNumber, Date fromObjection, Date toObjection) throws ValidationException { if ((objectionNumber == null || objectionNumber.trim().isEmpty()) && (fromObjection == null && toObjection == null)) throw new ValidationException("ObjectioNumber or ObjectionDate is mandatory", "ObjectioNumber or ObjectionDate is mandatory"); Criteria propertyCriteria = getCurrentSession().createCriteria(PropertyImpl.class, "propertyImpl") .add(Restrictions.eq("status", PropertyTaxConstants.STATUS_ISACTIVE)); DetachedCriteria detachCrtObjection = DetachedCriteria.forClass(RevisionPetition.class); detachCrtObjection.setProjection(Projections.projectionList().add(Projections.property("basicProperty"))); if (propertyTypeMasterId != null && propertyTypeMasterId > 0) { propertyCriteria.createAlias("propertyDetail", "propertyDetail"); propertyCriteria.createAlias("propertyDetail.propertyTypeMaster", "propertyTypeMaster"); propertyCriteria.add(Restrictions.eq("propertyTypeMaster.id", propertyTypeMasterId)); } if (objectionNumber != null && !objectionNumber.trim().isEmpty()) { detachCrtObjection.add(Restrictions.ilike("objectionNumber", objectionNumber)); } if (fromObjection != null && toObjection != null) { detachCrtObjection.add(Restrictions.between("recievedOn", fromObjection, toObjection)); } else if (fromObjection != null) { detachCrtObjection.add(Restrictions.ge("recievedOn", fromObjection)); } else if (toObjection != null) { detachCrtObjection.add(Restrictions.le("recievedOn", toObjection)); } propertyCriteria.add(Subqueries.propertyIn("basicProperty", detachCrtObjection)); return propertyCriteria.list(); }
From source file:org.encuestame.persistence.dao.imp.AbstractSocialAccount.java
License:Apache License
/** * Get social accounts stats./* w w w. j a v a 2 s .c o m*/ * @param socialAccount {@link SocialAccount}. * @return */ public HashMap<String, Long> getSocialAccountStats(final SocialAccount socialAccount) { final HashMap<String, Long> stats = new HashMap<String, Long>(); log.debug("getSocialAccountStats " + socialAccount.getId()); final DetachedCriteria criteria = DetachedCriteria.forClass(TweetPollSavedPublishedStatus.class); criteria.add(Restrictions.eq("socialAccount", socialAccount)); criteria.setProjection(Projections.rowCount()); @SuppressWarnings("unchecked") final List tweetPollstats = getHibernateTemplate().findByCriteria(criteria); log.debug("getSocialAccountStats " + tweetPollstats.size()); log.debug("getSocialAccountStats " + tweetPollstats); if (tweetPollstats.size() > 0) { stats.put("tweetpoll", Long.valueOf(tweetPollstats.get(0).toString())); } else { stats.put("tweetpoll", 0L); } //TODO: in the future we can add another stats. stats.put("poll", 0L); stats.put("survey", 0L); log.debug("getSocialAccountStats stats" + stats); return stats; }
From source file:org.encuestame.persistence.dao.imp.AccountDaoImp.java
License:Apache License
/** * Get list of id accounts only if are enabled. * @return list of id's.//from ww w .j a v a2s .co m */ public List<Long> getAccountsEnabled(final Boolean status) { final DetachedCriteria criteria = DetachedCriteria.forClass(Account.class); criteria.add(Restrictions.eq("enabled", status)); criteria.setProjection(Projections.id()); final List<Long> accountsId = (List<Long>) getHibernateTemplate().findByCriteria(criteria); return accountsId; }