@SuppressWarnings("rawtypes") private List findByCriteria(Criteria crit, int pageNo, int pageSize, Projection projection, Order... orders) { if ((pageNo <= 0 && pageNo != -1) || pageSize < 1) { return new ArrayList(); } crit.setProjection(projection); if (projection == null) { crit.setResultTransformer(Criteria.ROOT_ENTITY); } if (orders != null) { for (Order order : orders) { crit.addOrder(order); } } if (pageNo != -1) { crit.setFirstResult((pageNo - 1) * pageSize); crit.setMaxResults(pageSize); } return crit.list(); }
/** * @deprecated This method does not work well due to Hibernate bug HHH-817, nor does * AliasToBeanResultTransformer handle multi-level property values. * Therefore it should not be used. * * @param propertyNames * @param alias * @param aliasPath * @param domainClass * @return * * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817 */ @Deprecated public static Projection createAliasedProjectionList(final String[] propertyNames, final String alias, final String aliasPath, final Class<?> domainClass) { final ProjectionList projectionList = Projections.projectionList(); for (final String propertyName : propertyNames) { final Field field = ReflectionUtils.findField(domainClass, propertyName); if (!hasAssociationAnnotation(field)) { final String aliasedProperty = alias + "." + propertyName; projectionList .add(Projections.property(aliasedProperty), aliasedProperty); } } return projectionList; }
protected <T, R> Criteria getCriteria(Query<T, R> query) { final Criterion translated = queryTranslator.translate(query); if (log.isDebugEnabled()) { log.debug(translated); } 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; }
@Override public List<Long> getUnassignedDocumentIDsByCrisisID(Long crisisID, Integer count) { List<Long> docIDList = new ArrayList<Long>(); Criteria criteria = null; try { String aliasTable = "taskAssignments"; String order = "ASC"; String aliasTableKey = "taskAssignments.id.documentId"; String[] orderBy = {"valueAsTrainingSample", "documentId"}; Criterion criterion = Restrictions.conjunction() .add(Restrictions.eq("collection.id",crisisID)) .add(Restrictions.eq("hasHumanLabels",false)); // get just the documentIDs Projection projection = Projections.property("documentId"); Criterion aliasCriterion = (Restrictions.isNull(aliasTableKey)); criteria = createCriteria(criterion, order, orderBy, count, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN); docIDList = criteria.list(); return docIDList; } catch (Exception e) { logger.error("getByCriteriaWithAliasByOrder failed, criteria = " + criteria.toString(), e); throw new HibernateException("getByCriteriaWithAliasByOrder failed, criteria = " + criteria.toString()); } }
/** * find projection from criteria. * * @param criteria * Criteria * @return Projection */ public static Projection findProjection(Criteria criteria) { if (criteria instanceof CriteriaImpl) { return ((CriteriaImpl) criteria).getProjection(); } else { throw new IllegalArgumentException(criteria + " is not a CriteriaImpl"); } }
/** * 分页查询函数,使用已设好查询条件与排序的<code>Criteria</code>. * * @param criteria * 条件 * @param pageNo * 当前页号 * @param pageSize * 每页最大记录数 * @return 含总记录数和当前页数据的Page对象. */ @Transactional(readOnly = true) public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) { Assert.notNull(criteria); Assert.isTrue(pageNo >= 1, "pageNo should be eg 1"); Assert.isTrue(criteria instanceof CriteriaImpl); // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作 Projection projection = HibernateUtils.findProjection(criteria); List orderEntries = HibernateUtils.findOrderEntries(criteria); HibernateUtils.setOrderEntries(criteria, Collections.EMPTY_LIST); // 执行查询 Integer totalCount = this.getCount(criteria); // 将之前的Projection和OrderBy条件重新设回去 criteria.setProjection(projection); if (projection == null) { criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } HibernateUtils.setOrderEntries(criteria, orderEntries); // 返回分页对象 if (totalCount < 1) { return new Page(); } int start = (pageNo - 1) * pageSize; List result = criteria.setFirstResult(start).setMaxResults(pageSize) .list(); Page page = new Page(result, totalCount); page.setPageNo(pageNo); page.setPageSize(pageSize); return page; }
/** * Get the names of the columns constrained * by this criterion. */ @Override public String[] getColumnsUsingProjection( Criteria subcriteria, String propertyName) throws HibernateException { //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); String[] projectionColumns = null; if ( projection != null ) { projectionColumns = ( projection instanceof EnhancedProjection ? ( ( EnhancedProjection ) projection ).getColumnAliases( propertyName, 0, rootCriteria, this ) : projection.getColumnAliases( propertyName, 0 ) ); } if ( projectionColumns == null ) { //it does not refer to an alias of a projection, //look for a property try { return getColumns( propertyName, subcriteria ); } catch ( HibernateException he ) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName ); } else { throw he; } } } else { //it refers to an alias of a projection return projectionColumns; } }
@Override public Type getTypeUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException { //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); Type[] projectionTypes = projection == null ? null : projection.getTypes( propertyName, subcriteria, this ); if ( projectionTypes == null ) { try { //it does not refer to an alias of a projection, //look for a property return getType( subcriteria, propertyName ); } catch ( HibernateException he ) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getType( subcriteria, propertyName ); } else { throw he; } } } else { if ( projectionTypes.length != 1 ) { //should never happen, i think throw new QueryException( "not a single-length projection: " + propertyName ); } return projectionTypes[0]; } }
@Override public Criteria setProjection(Projection projection) { this.projection = projection; this.projectionCriteria = this; setResultTransformer( PROJECTION ); return this; }
@Override public Criteria setProjection(Projection projection) { CriteriaImpl.this.projection = projection; CriteriaImpl.this.projectionCriteria = this; setResultTransformer(PROJECTION); return this; }
/** * Get the names of the columns constrained * by this criterion. */ @Override public String[] getColumnsUsingProjection( Criteria subcriteria, String propertyName) throws HibernateException { //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); String[] projectionColumns = null; if ( projection != null ) { projectionColumns = ( projection instanceof EnhancedProjection ? ( (EnhancedProjection) projection ).getColumnAliases( propertyName, 0, rootCriteria, this ) : projection.getColumnAliases( propertyName, 0 ) ); } if ( projectionColumns == null ) { //it does not refer to an alias of a projection, //look for a property try { return getColumns( propertyName, subcriteria ); } catch (HibernateException he) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName ); } else { throw he; } } } else { //it refers to an alias of a projection return projectionColumns; } }
@Override public Type getTypeUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException { // propertyName = "columnId"; //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); Type[] projectionTypes = projection == null ? null : projection.getTypes( propertyName, subcriteria, this ); if ( projectionTypes == null ) { try { //it does not refer to an alias of a projection, //look for a property return getType( subcriteria, propertyName ); } catch (HibernateException he) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getType( subcriteria, propertyName ); } else { throw he; } } } else { if ( projectionTypes.length != 1 ) { //should never happen, i think throw new QueryException( "not a single-length projection: " + propertyName ); } return projectionTypes[0]; } }
@Override public Criteria setProjection(Projection projection) { this.projection = projection; this.projectionCriteria = this; setResultTransformer(PROJECTION); return this; }
@Override public Criteria setProjection(Projection projection) { CustomCriteriaImpl.this.projection = projection; CustomCriteriaImpl.this.projectionCriteria = this; setResultTransformer(PROJECTION); return this; }
@Override public String getOfficialSigSha1(String pkname) { Projection officialSigSha1 = Projections.property("officialSigSha1"); Criteria cri = getSession().createCriteria(App.class); cri.setProjection(officialSigSha1); cri.add(Restrictions.eq("pkname", pkname)); cri.add(Restrictions.isNotNull("officialSigSha1")); List<String> list = HibernateHelper.list(cri); if (list != null && !list.isEmpty()) { return list.get(0); } return null; }
@Override public String getOfficialSigSha1(Session session, String pkname) { Projection officialSigSha1 = Projections.property("officialSigSha1"); Criteria cri = session.createCriteria(App.class); cri.setProjection(officialSigSha1); cri.add(Restrictions.eq("pkname", pkname)); cri.add(Restrictions.isNotNull("officialSigSha1")); List<String> list = HibernateHelper.list(cri); if (list != null && !list.isEmpty()) { return list.get(0); } return null; }
/** * Get the names of the columns constrained * by this criterion. */ public String[] getColumnsUsingProjection( Criteria subcriteria, String propertyName) throws HibernateException { //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); String[] projectionColumns = projection == null ? null : projection.getColumnAliases( propertyName, 0 ); if ( projectionColumns == null ) { //it does not refer to an alias of a projection, //look for a property try { return getColumns( propertyName, subcriteria ); } catch ( HibernateException he ) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName ); } else { throw he; } } } else { //it refers to an alias of a projection return projectionColumns; } }
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException { //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); Type[] projectionTypes = projection == null ? null : projection.getTypes( propertyName, subcriteria, this ); if ( projectionTypes == null ) { try { //it does not refer to an alias of a projection, //look for a property return getType( subcriteria, propertyName ); } catch ( HibernateException he ) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getType( subcriteria, propertyName ); } else { throw he; } } } else { if ( projectionTypes.length != 1 ) { //should never happen, i think throw new QueryException( "not a single-length projection: " + propertyName ); } return projectionTypes[0]; } }
@SuppressWarnings("unchecked") @Test public void testProjectionOrderShouldSortAscByDefault() { final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L); City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L); this.cityDao.save(p1); this.cityDao.save(p2); this.cityDao.save(p3); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); Projection projection = Projections.property("featureId").as( "featureId"); testCriteria.setProjection(projection).addOrder( new ProjectionOrder("featureId")).setResultTransformer( Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } }; List<_CityDTO> cities = (List<_CityDTO>) testDao .testCallback(hibernateCallback); assertEquals(3, cities.size()); assertEquals("1", cities.get(0).getFeatureId().toString()); assertEquals("2", cities.get(1).getFeatureId().toString()); assertEquals("3", cities.get(2).getFeatureId().toString()); }
@SuppressWarnings("unchecked") @Test public void testNativeSQLOrderShouldSortAscByDefault() { final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L); City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L); this.cityDao.save(p1); this.cityDao.save(p2); this.cityDao.save(p3); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); Projection projection = Projections.property("featureId").as( "featureId"); testCriteria.setProjection(projection).addOrder( new NativeSQLOrder("featureId")).setResultTransformer( Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } }; List<_CityDTO> cities = (List<_CityDTO>) testDao .testCallback(hibernateCallback); assertEquals(3, cities.size()); assertEquals("1", cities.get(0).getFeatureId().toString()); assertEquals("2", cities.get(1).getFeatureId().toString()); assertEquals("3", cities.get(2).getFeatureId().toString()); }
@SuppressWarnings("unchecked") @Test public void testNativeSQLOrderShouldSortDesc() { final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L); City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L); this.cityDao.save(p1); this.cityDao.save(p2); this.cityDao.save(p3); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); Projection projection = Projections.property("featureId").as( "featureId"); testCriteria.setProjection(projection).addOrder( new NativeSQLOrder("featureId", false)) .setResultTransformer( Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } }; List<_CityDTO> cities = (List<_CityDTO>) testDao .testCallback(hibernateCallback); assertEquals(3, cities.size()); assertEquals("3", cities.get(0).getFeatureId().toString()); assertEquals("2", cities.get(1).getFeatureId().toString()); assertEquals("1", cities.get(2).getFeatureId().toString()); }
/** * Keeps track of the current projection. * <p> * {@inheritDoc} */ @Override public DetachedCriteria setProjection(Projection proj) { DetachedCriteria returnedCrit = super.setProjection(proj); currentProjection = proj; return returnedCrit; }
public PageSupport find(final CriteriaQuery cq, final boolean isOffset) { return (PageSupport) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { cq.add();// 增加条件 Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(session); // 得到总行数 Projection projection = Projections.rowCount(); Object result = criteria.setProjection(projection).uniqueResult(); long allCounts = ((Number) result).longValue(); criteria.setProjection(null);// 还原 int curPageNO = PagerUtil.getCurPageNO(cq.getCurPage());// 当前页 int offset = PagerUtil.getOffset(allCounts, curPageNO, cq.getPageSize()); if (cq.getOrderList() != null) { for (Order order : cq.getOrderList()) { criteria.addOrder(order); } } if (isOffset) { criteria.setFirstResult(offset); criteria.setMaxResults(cq.getPageSize()); } return new PageSupport(criteria.list(), cq.getMyaction(), offset, curPageNO, allCounts, cq.getPageSize(), cq .getPageProvider()); } }); }
/** * A group-by-having projection with an operator and value. * * @param groupByProperty * the group by property * @param projection * the having projection * @param op * an operator to apply to the having * @param value * the value of a having based on the operator */ public GroupByHavingProjection(final String groupByProperty, final Projection projection, final Relation op, final Object value) { super(groupByProperty, true); ValidationUtil.validateNotNull("groupByProperty", groupByProperty); ValidationUtil.validateNotNull("projection", projection); ValidationUtil.validateNotNull("op", op); this.projection = projection; this.groupByProperty = groupByProperty; this.op = op; this.value = value; }
/** * Visits a collection expression. */ public static Projection countProjection(final String propertyName, final boolean distinct) { return distinct ? Projections.countDistinct(propertyName) : Projections .count(propertyName); }
/** * @deprecated This method does not work well due to Hibernate bug HHH-817, nor does * AliasToBeanResultTransformer handle multi-level property values. * Therefore it should not be used. * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817 */ @Deprecated public static Projection createProjectionList(final String identifierProperty, final Type identifierType, final String[] propertyNames, final Class<?> domainClass) { final ProjectionList projectionList = Projections.projectionList(); if (identifierType.isComponentType()) { final String[] idProperties = ((ComponentType) (identifierType)) .getPropertyNames(); for (final String idProperty : idProperties) { final String idPath = identifierProperty + "." + idProperty; projectionList.add(Projections.property(idPath)); } } else { projectionList.add(Projections.id()); } for (final String propertyName : propertyNames) { final Field field = ReflectionUtils.findField(domainClass, propertyName); if (!hasAssociationAnnotation(field)) { projectionList.add(Projections.property(propertyName), propertyName); } } return projectionList; }
@Override public <T, R> Projection translateProjection(Query<T, R> query) { if (query.getReturnFields().size() > 0) { ProjectionList projectionList = Projections.projectionList(); for (String returnField : query.getReturnFields()) { projectionList.add(Projections.property(returnField)); } return projectionList; } else { return null; } }
@Test public void translateProjection_some() { ProjectionList expected = Projections.projectionList() .add(Projections.property("a")).add(Projections.property("b")) .add(Projections.property("c")); Projection actual = translator.translateProjection(QueryBuilder.builderFor( String.class, String.class, "a", "b", "c").build()); assertArrayEquals(expected.getAliases(), actual.getAliases()); }
public Criteria createCriteria(Criterion criterion, String order, String[] orderBy, Integer count, String aliasTable, Criterion aliasCriterion, Projection[] projections, JoinType joinType) { Session session = getCurrentSession(); List fetchedList = new ArrayList(); //logger.info("Entity: " + entityClass + ", current Session = " + session); Criteria criteria = session.createCriteria(entityClass); criteria.add(criterion); criteria.createAlias(aliasTable, aliasTable, joinType).add(aliasCriterion); if (orderBy != null) { for(int i = 0; i< orderBy.length; i++){ if (order != null && order.equalsIgnoreCase("desc")) { criteria.addOrder(Order.desc(orderBy[i])); } else { criteria.addOrder(Order.asc(orderBy[i])); } } } if(count != null && count > 0){ criteria.setMaxResults(count); } // set projections setProjections(criteria, projections); return criteria; }
private void setProjections(Criteria criteria, Projection[] projections) { ProjectionList projList = Projections.projectionList(); if(projections != null && projections.length > 0) { for(Projection projection : projections) { projList.add(projection); } criteria.setProjection(projList); } }
@Override public Integer getDocumentCountForNominalLabelAndCrisis(Long nominalLabelID, String crisisCode) { if (nominalLabelID != null) { String aliasTable = "documentNominalLabels"; String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId"; String[] orderBy = {"documentId"}; Criteria criteria = null; try { CollectionDTO cdto = crisisEJB.getCrisisByCode(crisisCode); Criterion criterion = Restrictions.conjunction() .add(Restrictions.eq("collection.id",cdto.getCrisisID())) .add(Restrictions.eq("hasHumanLabels", true)); Criterion aliasCriterion = Restrictions.eq(aliasTableKeyField, nominalLabelID); // get just the documentIDs Projection projection = Projections.property("documentId"); //List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion); criteria = createCriteria(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN); List<Long> docIDList = criteria.list(); if (docIDList != null && !docIDList.isEmpty()) { return docIDList.size(); } } catch (Exception e) { logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e); return 0; } } return 0; }
@Override public List<DocumentDTO> getDocumentForNominalLabelAndCrisis(List<Long> nominalLabelID, Long crisisId) { List<DocumentDTO> dtoList = new ArrayList<DocumentDTO>(); if (nominalLabelID != null) { String aliasTable = "documentNominalLabels"; String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId"; Criteria criteria = null; try { Criterion criterion = Restrictions.conjunction() .add(Restrictions.eq("collection.id", crisisId)) .add(Restrictions.eq("hasHumanLabels", true)); Criterion aliasCriterion = Restrictions.in(aliasTableKeyField, nominalLabelID); // get just the documentIDs Projection projection = Projections.property("documentId"); //List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion); criteria = createCriteria(criterion, null, null, null, aliasTable, aliasCriterion, null, JoinType.INNER_JOIN); List<Document> docList = criteria.list(); if (docList != null && !docList.isEmpty()) { for (Document doc : docList) { DocumentDTO dto = new DocumentDTO(doc); dtoList.add(dto); } } } catch (Exception e) { logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e); } } return dtoList; }
public Projection getProjection() { return projection; }
public EntityCriteria<T> setProjection(Projection projection) { criteria.setProjection(projection); return this; }
public Criteria setProjection(Projection projection) { this.projection = projection; this.projectionCriteria = this; setResultTransformer( PROJECTION ); return this; }
public Criteria setProjection(Projection projection) { CriteriaImpl.this.projection = projection; CriteriaImpl.this.projectionCriteria = this; setResultTransformer(PROJECTION); return this; }
@SuppressWarnings("unchecked") @Test public void testProjectionOrderShouldSortDesc() { final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L); City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L); this.cityDao.save(p1); this.cityDao.save(p2); this.cityDao.save(p3); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); Projection projection = Projections.property("featureId").as( "featureId"); testCriteria.setProjection(projection).addOrder( new ProjectionOrder("featureId", false)) .setResultTransformer( Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } }; List<_CityDTO> cities = (List<_CityDTO>) testDao .testCallback(hibernateCallback); assertEquals(3, cities.size()); assertEquals("3", cities.get(0).getFeatureId().toString()); assertEquals("2", cities.get(1).getFeatureId().toString()); assertEquals("1", cities.get(2).getFeatureId().toString()); }