List of usage examples for org.hibernate Criteria setProjection
public Criteria setProjection(Projection projection);
From source file:com.denimgroup.threadfix.data.dao.hibernate.VulnerabilitySearchCriteriaConstructor.java
License:Mozilla Public License
private void addChannelTypeRestrictions() { // Limit scanner if present if (parameters.getChannelTypes() != null && !parameters.getChannelTypes().isEmpty()) { List<Integer> channelTypeIds = list(); for (ChannelType channelType : parameters.getChannelTypes()) { if (channelType.getId() != null) { channelTypeIds.add(channelType.getId()); }/*from w w w . j av a2s .com*/ } if (!channelTypeIds.isEmpty()) { Criteria subCriteria = session.createCriteria(Finding.class); subCriteria.createAlias("scan", "myScan"); subCriteria.createAlias("myScan.applicationChannel", "myApplicationChannel"); subCriteria.createAlias("myApplicationChannel.channelType", "myChannelType"); subCriteria.add(Restrictions.in("myChannelType.id", channelTypeIds)); subCriteria.setProjection(Projections.property("vulnerability.id")); List<Integer> ids = (List<Integer>) subCriteria.list(); if (ids.isEmpty()) { LOG.debug("Got no valid Scanner type IDs."); ids.add(0); // should yield no results // throw an exception here? } else { LOG.debug("Adding scanner restriction: " + channelTypeIds); } criteria.add(Restrictions.in("id", ids)); } } }
From source file:com.dosport.hibernate.utils.HibernateDao.java
License:Apache License
/** * countCriteria.//from w ww.jav a2 s . c om */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected long countCriteriaResult(final Criteria c) { CriteriaImpl impl = (CriteriaImpl) c; // Projection?ResultTransformer?OrderBy??,??Count? Projection projection = impl.getProjection(); ResultTransformer transformer = impl.getResultTransformer(); List<CriteriaImpl.OrderEntry> orderEntries = null; try { orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries"); ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList()); } catch (Exception e) { logger.error("??:{}", e.getMessage()); } // Count Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult(); long totalCount = (totalCountObject != null) ? totalCountObject : 0; // ?Projection,ResultTransformerOrderBy?? c.setProjection(projection); if (projection == null) { c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } if (transformer != null) { c.setResultTransformer(transformer); } try { ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries); } catch (Exception e) { logger.error("??:{}", e.getMessage()); } return totalCount; }
From source file:com.eharmony.matching.seeking.executor.hibernate.HibernateQueryExecutor.java
License:Apache License
protected <T, R> Criteria getCriteria(Query<T, R> query) { final Criterion translated = queryTranslator.translate(query); if (log.isDebugEnabled()) { log.debug(translated);/*from w ww .j a v a2s . c o m*/ } final Criteria criteria = getSession().createCriteria(query.getEntityClass()); criteria.add(translated); final List<Order> orders = queryTranslator.translateOrder(query).get(); for (final Order order : orders) { criteria.addOrder(order); } final Projection projection = queryTranslator.translateProjection(query); if (projection != null) { criteria.setProjection(projection); } if (query.getMaxResults() != null) { criteria.setMaxResults(query.getMaxResults()); } return criteria; }
From source file:com.eryansky.common.orm.core.hibernate.support.HibernateSupportDao.java
License:Apache License
/** * countCriteria.//from w w w . j a va 2s . c o m * * @param c Criteria * * @return long */ protected long countCriteriaResult(Criteria c) { CriteriaImpl impl = (CriteriaImpl) c; // Projection?ResultTransformer?OrderBy??,??Count? Projection projection = impl.getProjection(); ResultTransformer transformer = impl.getResultTransformer(); List<CriteriaImpl.OrderEntry> orderEntries = null; try { orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries"); ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList()); } catch (Exception e) { e.printStackTrace(); } // Count Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult(); long totalCount = (totalCountObject != null) ? totalCountObject : 0; // ?Projection,ResultTransformerOrderBy?? c.setProjection(projection); if (projection == null) { c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } if (transformer != null) { c.setResultTransformer(transformer); } try { ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries); } catch (Exception e) { e.printStackTrace(); } return totalCount; }
From source file:com.eucalyptus.cloudwatch.common.internal.domain.alarms.AlarmManager.java
License:Open Source License
public static Long countMetricAlarms(String accountId) { try (final TransactionResource db = Entities.transactionFor(AlarmEntity.class)) { Criteria criteria = Entities.createCriteria(AlarmEntity.class); criteria = criteria.setProjection(Projections.rowCount()); if (accountId != null) { criteria = criteria.add(Restrictions.eq("accountId", accountId)); }//from ww w. j a v a2 s . co m return (Long) criteria.uniqueResult(); } }
From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java
License:Open Source License
public static List<Collection<MetricStatistics>> getManyMetricStatistics( List<GetMetricStatisticsParams> getMetricStatisticsParamses) { if (getMetricStatisticsParamses == null) throw new IllegalArgumentException("getMetricStatisticsParamses can not be null"); Date now = new Date(); Map<GetMetricStatisticsParams, Collection<MetricStatistics>> resultMap = Maps.newHashMap(); Multimap<Class, GetMetricStatisticsParams> hashGroupMap = LinkedListMultimap.create(); for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) { if (getMetricStatisticsParams == null) throw new IllegalArgumentException("getMetricStatisticsParams can not be null"); getMetricStatisticsParams.validate(now); Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet( getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash()); hashGroupMap.put(metricEntityClass, getMetricStatisticsParams); }//from ww w . ja v a 2s . co m for (Class metricEntityClass : hashGroupMap.keySet()) { try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) { // set some global criteria to start (for narrowing?) Date minDate = null; Date maxDate = null; Junction disjunction = Restrictions.disjunction(); Map<GetMetricStatisticsParams, TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>> multiAggregationMap = Maps .newHashMap(); for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap.get(metricEntityClass)) { multiAggregationMap.put(getMetricStatisticsParams, new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>( GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE)); Junction conjunction = Restrictions.conjunction(); conjunction = conjunction .add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime())); conjunction = conjunction .add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime())); conjunction = conjunction .add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId())); conjunction = conjunction .add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName())); conjunction = conjunction .add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace())); conjunction = conjunction.add( Restrictions.eq("dimensionHash", hash(getMetricStatisticsParams.getDimensionMap()))); if (getMetricStatisticsParams.getUnits() != null) { conjunction = conjunction .add(Restrictions.eq("units", getMetricStatisticsParams.getUnits())); } disjunction = disjunction.add(conjunction); if (minDate == null || getMetricStatisticsParams.getStartTime().before(minDate)) { minDate = getMetricStatisticsParams.getStartTime(); } if (maxDate == null || getMetricStatisticsParams.getEndTime().after(maxDate)) { maxDate = getMetricStatisticsParams.getEndTime(); } } Criteria criteria = Entities.createCriteria(metricEntityClass); criteria = criteria.add(Restrictions.lt("timestamp", maxDate)); criteria = criteria.add(Restrictions.ge("timestamp", minDate)); criteria = criteria.add(disjunction); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.max("sampleMax")); projectionList.add(Projections.min("sampleMin")); projectionList.add(Projections.sum("sampleSize")); projectionList.add(Projections.sum("sampleSum")); projectionList.add(Projections.groupProperty("units")); projectionList.add(Projections.groupProperty("timestamp")); projectionList.add(Projections.groupProperty("accountId")); projectionList.add(Projections.groupProperty("metricName")); projectionList.add(Projections.groupProperty("metricType")); projectionList.add(Projections.groupProperty("namespace")); projectionList.add(Projections.groupProperty("dimensionHash")); criteria.setProjection(projectionList); criteria.addOrder(Order.asc("timestamp")); ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY); while (results.next()) { MetricEntity me = getMetricEntity(results); for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap .get(metricEntityClass)) { if (metricDataMatches(getMetricStatisticsParams, me)) { Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = multiAggregationMap .get(getMetricStatisticsParams); GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me, getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensionHash()); MetricStatistics item = new MetricStatistics(me, getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensions()); if (!aggregationMap.containsKey(key)) { aggregationMap.put(key, item); } else { MetricStatistics totalSoFar = aggregationMap.get(key); totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax())); totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin())); totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize()); totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum()); } } } } for (GetMetricStatisticsParams getMetricStatisticsParams : multiAggregationMap.keySet()) { resultMap.put(getMetricStatisticsParams, multiAggregationMap.get(getMetricStatisticsParams).values()); } } } List<Collection<MetricStatistics>> resultList = Lists.newArrayList(); for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) { if (resultMap.get(getMetricStatisticsParams) == null) { resultList.add(new ArrayList<MetricStatistics>()); } else { resultList.add(resultMap.get(getMetricStatisticsParams)); } } return resultList; }
From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java
License:Open Source License
public static Collection<MetricStatistics> getMetricStatistics( GetMetricStatisticsParams getMetricStatisticsParams) { if (getMetricStatisticsParams == null) throw new IllegalArgumentException("getMetricStatisticsParams can not be null"); Date now = new Date(); getMetricStatisticsParams.validate(now); Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet( getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash()); Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>( GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE); try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) { Criteria criteria = Entities.createCriteria(metricEntityClass); criteria = criteria.add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId())); criteria = criteria.add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName())); criteria = criteria.add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace())); criteria = criteria.add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime())); criteria = criteria.add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime())); criteria = criteria.add(Restrictions.eq("dimensionHash", getMetricStatisticsParams.getDimensionHash())); if (getMetricStatisticsParams.getUnits() != null) { criteria = criteria.add(Restrictions.eq("units", getMetricStatisticsParams.getUnits())); }/*from w w w .j a v a 2s.c o m*/ ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.max("sampleMax")); projectionList.add(Projections.min("sampleMin")); projectionList.add(Projections.sum("sampleSize")); projectionList.add(Projections.sum("sampleSum")); projectionList.add(Projections.groupProperty("units")); projectionList.add(Projections.groupProperty("timestamp")); criteria.setProjection(projectionList); criteria.addOrder(Order.asc("timestamp")); ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY); while (results.next()) { MetricEntity me = getMetricEntity(getMetricStatisticsParams.getAccountId(), getMetricStatisticsParams.getMetricName(), getMetricStatisticsParams.getNamespace(), getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash(), results); GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me, getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensionHash()); MetricStatistics item = new MetricStatistics(me, getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensions()); if (!aggregationMap.containsKey(key)) { aggregationMap.put(key, item); } else { MetricStatistics totalSoFar = aggregationMap.get(key); totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax())); totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin())); totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize()); totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum()); } } } return Lists.newArrayList(aggregationMap.values()); }
From source file:com.eucalyptus.cloudwatch.domain.alarms.AlarmManager.java
License:Open Source License
public static Long countMetricAlarms(String accountId) { EntityTransaction db = Entities.get(AlarmEntity.class); try {//from w ww. j a v a 2s.com Criteria criteria = Entities.createCriteria(AlarmEntity.class); criteria = criteria.setProjection(Projections.rowCount()); if (accountId != null) { criteria = criteria.add(Restrictions.eq("accountId", accountId)); } return (Long) criteria.uniqueResult(); } catch (RuntimeException ex) { Logs.extreme().error(ex, ex); throw ex; } finally { db.rollback(); } }
From source file:com.evolveum.midpoint.repo.sql.query.custom.ShadowQueryWithDisjunction.java
License:Apache License
@Override public RQuery createQuery(ObjectQuery objectQuery, Class<? extends ObjectType> type, Collection<SelectorOptions<GetOperationOptions>> options, boolean countingObjects, Session session) { DetachedCriteria c1 = DetachedCriteria.forClass(ClassMapper.getHQLTypeClass(ShadowType.class), "s"); c1.createCriteria("strings", "s1", JoinType.LEFT_OUTER_JOIN); ParsedQuery parsedQuery = parse(objectQuery); Conjunction conjunction = Restrictions.conjunction(); conjunction//from w w w . j av a 2 s. c o m .add(Restrictions.eq("resourceRef.targetOid", parsedQuery.refFilter.getValues().get(0).getOid())); Disjunction disjunction = Restrictions.disjunction(); disjunction.add(createAttributeEq(parsedQuery.eqUidFilter, parsedQuery.eqUidFilter.getPath().lastNamed().getName())); disjunction.add(createAttributeEq(parsedQuery.eqNameFilter, SchemaConstantsGenerated.ICF_S_NAME)); conjunction.add(disjunction); c1.add(conjunction); if (countingObjects) { c1.setProjection(Projections.countDistinct("s.oid")); return new RQueryCriteriaImpl(c1.getExecutableCriteria(session)); } c1.setProjection(Projections.distinct(Projections.property("s.oid"))); Criteria cMain = session.createCriteria(ClassMapper.getHQLTypeClass(ShadowType.class), "o"); cMain.add(Subqueries.propertyIn("oid", c1)); if (objectQuery != null && objectQuery.getPaging() != null) { cMain = updatePagingAndSorting(cMain, type, objectQuery.getPaging()); } ProjectionList projections = Projections.projectionList(); projections.add(Projections.property("fullObject")); projections.add(Projections.property("stringsCount")); projections.add(Projections.property("longsCount")); projections.add(Projections.property("datesCount")); projections.add(Projections.property("referencesCount")); projections.add(Projections.property("polysCount")); projections.add(Projections.property("booleansCount")); cMain.setProjection(projections); cMain.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); return new RQueryCriteriaImpl(cMain); }
From source file:com.evolveum.midpoint.repo.sql.query.QueryInterpreter.java
License:Apache License
public Criteria interpret(ObjectQuery query, Class<? extends ObjectType> type, Collection<SelectorOptions<GetOperationOptions>> options, PrismContext prismContext, boolean countingObjects, Session session) throws QueryException { Validate.notNull(type, "Type must not be null."); Validate.notNull(session, "Session must not be null."); Validate.notNull(prismContext, "Prism context must not be null."); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Interpreting query for type '{}', query:\n{}", new Object[] { type, query }); }/*from w w w .j a v a2 s . c om*/ Criteria criteria; if (query != null && query.getFilter() != null) { criteria = interpretQuery(query, type, prismContext, session); } else { criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type)); } if (!countingObjects && query != null && query.getPaging() != null) { criteria = updatePagingAndSorting(criteria, type, query.getPaging()); } if (!countingObjects) { ProjectionList projections = Projections.projectionList(); projections.add(Projections.property("fullObject")); projections.add(Projections.property("stringsCount")); projections.add(Projections.property("longsCount")); projections.add(Projections.property("datesCount")); projections.add(Projections.property("referencesCount")); projections.add(Projections.property("polysCount")); criteria.setProjection(projections); } return criteria; }