private void createAssociationPathCriteriaMap() { final Iterator<CriteriaImpl.Subcriteria> iter = rootCriteria.iterateSubcriteria(); while ( iter.hasNext() ) { CriteriaImpl.Subcriteria crit = iter.next(); String wholeAssociationPath = getWholeAssociationPath( crit ); Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit ); if ( old != null ) { throw new QueryException( "duplicate association path: " + wholeAssociationPath ); } JoinType joinType = crit.getJoinType(); old = associationPathJoinTypesMap.put( wholeAssociationPath, joinType ); if ( old != null ) { // TODO : not so sure this is needed... throw new QueryException( "duplicate association path: " + wholeAssociationPath ); } if ( crit.getWithClause() != null ) { this.withClauseMap.put( wholeAssociationPath, crit.getWithClause() ); } } }
public static String showSql(Criteria criteria){ try { CriteriaImpl c = (CriteriaImpl) criteria; SessionImpl s = (SessionImpl) c.getSession(); SessionFactoryImplementor factory = (SessionFactoryImplementor) s.getSessionFactory(); String[] implementors = factory.getImplementors(c.getEntityOrClassName()); LoadQueryInfluencers lqis = new LoadQueryInfluencers(); CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable) factory.getEntityPersister(implementors[0]), factory, c, implementors[0], lqis); Field f = OuterJoinLoader.class.getDeclaredField("sql"); f.setAccessible(true); return (String) f.get(loader); }catch (Exception e){ e.printStackTrace(); return ""; } }
@Override public Object clone() { final CriteriaImpl impl = (CriteriaImpl) criteria; final HibernateSession hibernateSession = (HibernateSession) getSession(); final GrailsHibernateTemplate hibernateTemplate = (GrailsHibernateTemplate) hibernateSession.getNativeInterface(); return hibernateTemplate.execute(new GrailsHibernateTemplate.HibernateCallback<Object>() { @Override public HibernateQuery doInHibernate(Session session) throws HibernateException, SQLException { Criteria newCriteria = session.createCriteria(impl.getEntityOrClassName()); Iterator iterator = impl.iterateExpressionEntries(); while (iterator.hasNext()) { CriteriaImpl.CriterionEntry entry = (CriteriaImpl.CriterionEntry) iterator.next(); newCriteria.add(entry.getCriterion()); } Iterator subcriteriaIterator = impl.iterateSubcriteria(); while (subcriteriaIterator.hasNext()) { CriteriaImpl.Subcriteria sub = (CriteriaImpl.Subcriteria) subcriteriaIterator.next(); newCriteria.createAlias(sub.getPath(), sub.getAlias(), sub.getJoinType(), sub.getWithClause()); } return new HibernateQuery(newCriteria, hibernateSession, entity); } }); }
@SuppressWarnings("unused") public static boolean isExistAlias(DetachedCriteria impl, String path) { try { Field field = DetachedCriteria.class.getDeclaredField("impl"); field.setAccessible(true); CriteriaImpl criteriaImpl = (CriteriaImpl) field.get(impl); Iterator iterator = criteriaImpl.iterateSubcriteria(); for (; iterator.hasNext(); ) { Subcriteria subcriteria = (Subcriteria) iterator.next(); if (subcriteria.getPath().equals(path)) { return true; } } return false; } catch (Exception e) { return false; } }
/** * 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; }
private SessionImplementor deriveRootSession(Criteria criteria) { if ( criteria instanceof CriteriaImpl ) { return ( (CriteriaImpl) criteria ).getSession(); } else if ( criteria instanceof CriteriaImpl.Subcriteria ) { return deriveRootSession( ( (CriteriaImpl.Subcriteria) criteria ).getParent() ); } else { // could happen for custom Criteria impls. Not likely, but... // for long term solution, see HHH-3514 return null; } }
public CriteriaJoinWalker( final OuterJoinLoadable persister, final CriteriaQueryTranslator translator, final SessionFactoryImplementor factory, final CriteriaImpl criteria, final String rootEntityName, final LoadQueryInfluencers loadQueryInfluencers) { this( persister, translator, factory, criteria, rootEntityName, loadQueryInfluencers, null ); }
public CriteriaJoinWalker( final OuterJoinLoadable persister, final CriteriaQueryTranslator translator, final SessionFactoryImplementor factory, final CriteriaImpl criteria, final String rootEntityName, final LoadQueryInfluencers loadQueryInfluencers, final String alias) { super( persister, factory, loadQueryInfluencers, alias ); this.translator = translator; querySpaces = translator.getQuerySpaces(); if ( translator.hasProjection() ) { initProjection( translator.getSelect(), translator.getWhereCondition(), translator.getOrderBy(), translator.getGroupBy(), LockOptions.NONE ); resultTypes = translator.getProjectedTypes(); userAliases = translator.getProjectedAliases(); includeInResultRow = new boolean[ resultTypes.length ]; Arrays.fill( includeInResultRow, true ); } else { initAll( translator.getWhereCondition(), translator.getOrderBy(), LockOptions.NONE ); // root entity comes last userAliasList.add( criteria.getAlias() ); //root entity comes *last* resultTypeList.add( translator.getResultType( criteria ) ); includeInResultRowList.add( true ); userAliases = ArrayHelper.toStringArray( userAliasList ); resultTypes = ArrayHelper.toTypeArray( resultTypeList ); includeInResultRow = ArrayHelper.toBooleanArray( includeInResultRowList ); } }
public CriteriaLoader( final OuterJoinLoadable persister, final SessionFactoryImplementor factory, final CriteriaImpl criteria, final String rootEntityName, final LoadQueryInfluencers loadQueryInfluencers) throws HibernateException { super( factory, loadQueryInfluencers ); translator = new CriteriaQueryTranslator( factory, criteria, rootEntityName, CriteriaQueryTranslator.ROOT_SQL_ALIAS ); querySpaces = translator.getQuerySpaces(); CriteriaJoinWalker walker = new CriteriaJoinWalker( persister, translator, factory, criteria, rootEntityName, loadQueryInfluencers ); initFromWalker(walker); userAliases = walker.getUserAliases(); resultTypes = walker.getResultTypes(); includeInResultRow = walker.includeInResultRow(); resultRowLength = ArrayHelper.countTrue( includeInResultRow ); postInstantiate(); }
public CriteriaQueryTranslator( final SessionFactoryImplementor factory, final CriteriaImpl criteria, final String rootEntityName, final String rootSQLAlias, CriteriaQuery outerQuery) throws HibernateException { this( factory, criteria, rootEntityName, rootSQLAlias ); outerQueryTranslator = outerQuery; }
public CriteriaQueryTranslator( final SessionFactoryImplementor factory, final CriteriaImpl criteria, final String rootEntityName, final String rootSQLAlias) throws HibernateException { this.rootCriteria = criteria; this.rootEntityName = rootEntityName; this.sessionFactory = factory; this.rootSQLAlias = rootSQLAlias; this.helper = new SessionFactoryHelper(factory); createAliasCriteriaMap(); createAssociationPathCriteriaMap(); createCriteriaEntityNameMap(); createCriteriaSQLAliasMap(); }
private void createAliasCriteriaMap() { aliasCriteriaMap.put( rootCriteria.getAlias(), rootCriteria ); Iterator<CriteriaImpl.Subcriteria> iter = rootCriteria.iterateSubcriteria(); while ( iter.hasNext() ) { Criteria subcriteria = iter.next(); if ( subcriteria.getAlias() != null ) { Object old = aliasCriteriaMap.put( subcriteria.getAlias(), subcriteria ); if ( old != null ) { throw new QueryException( "duplicate alias: " + subcriteria.getAlias() ); } } } }
private String getWholeAssociationPath(CriteriaImpl.Subcriteria subcriteria) { String path = subcriteria.getPath(); // some messy, complex stuff here, since createCriteria() can take an // aliased path, or a path rooted at the creating criteria instance Criteria parent = null; if ( path.indexOf( '.' ) > 0 ) { // if it is a compound path String testAlias = StringHelper.root( path ); if ( !testAlias.equals( subcriteria.getAlias() ) ) { // and the qualifier is not the alias of this criteria // -> check to see if we belong to some criteria other // than the one that created us parent = aliasCriteriaMap.get( testAlias ); } } if ( parent == null ) { // otherwise assume the parent is the the criteria that created us parent = subcriteria.getParent(); } else { path = StringHelper.unroot( path ); } if ( parent.equals( rootCriteria ) ) { // if its the root criteria, we are done return path; } else { // otherwise, recurse return getWholeAssociationPath( ( CriteriaImpl.Subcriteria ) parent ) + '.' + path; } }
public String getWhereCondition() { StringBuilder condition = new StringBuilder( 30 ); Iterator<CriteriaImpl.CriterionEntry> criterionIterator = rootCriteria.iterateExpressionEntries(); while ( criterionIterator.hasNext() ) { CriteriaImpl.CriterionEntry entry = criterionIterator.next(); String sqlString = entry.getCriterion().toSqlString( entry.getCriteria(), this ); condition.append( sqlString ); if ( criterionIterator.hasNext() ) { condition.append( " and " ); } } return condition.toString(); }
public String getOrderBy() { StringBuilder orderBy = new StringBuilder( 30 ); Iterator<CriteriaImpl.OrderEntry> criterionIterator = rootCriteria.iterateOrderings(); while ( criterionIterator.hasNext() ) { CriteriaImpl.OrderEntry oe = criterionIterator.next(); orderBy.append( oe.getOrder().toSqlString( oe.getCriteria(), this ) ); if ( criterionIterator.hasNext() ) { orderBy.append( ", " ); } } return orderBy.toString(); }
@SuppressWarnings("rawtypes") public int queryCount(DetachedCriteria detachedCriteria,String dataSourceName){ Session session=this.getSessionFactory(dataSourceName).openSession(); try{ org.hibernate.Criteria criteria=detachedCriteria.getExecutableCriteria(session); try { Field field = CriteriaImpl.class.getDeclaredField("orderEntries"); field.setAccessible(true); field.set(criteria,new ArrayList()); } catch (Exception e) { e.printStackTrace(); } int totalCount=0; Object totalObject=criteria.setProjection(Projections.rowCount()).uniqueResult(); if(totalObject instanceof Integer){ totalCount=(Integer)totalObject; }else if(totalObject instanceof Long){ totalCount=((Long)totalObject).intValue(); }else if (totalObject != null) { throw new RuntimeException("Can not convert ["+totalObject+"] to a int value when query entity total count!"); } return totalCount; }finally{ session.flush(); session.close(); } }
@Override public int getTotalCount() { if (totalCount == Integer.MIN_VALUE) { totalCount = hibernateTemplate.execute(new GrailsHibernateTemplate.HibernateCallback<Integer>() { public Integer doInHibernate(Session session) throws HibernateException, SQLException { CriteriaImpl impl = (CriteriaImpl) criteria; Criteria totalCriteria = session.createCriteria(impl.getEntityOrClassName()); hibernateTemplate.applySettings(totalCriteria); Iterator iterator = impl.iterateExpressionEntries(); while (iterator.hasNext()) { CriteriaImpl.CriterionEntry entry = (CriteriaImpl.CriterionEntry) iterator.next(); totalCriteria.add(entry.getCriterion()); } Iterator subcriteriaIterator = impl.iterateSubcriteria(); while (subcriteriaIterator.hasNext()) { CriteriaImpl.Subcriteria sub = (CriteriaImpl.Subcriteria) subcriteriaIterator.next(); totalCriteria.createAlias(sub.getPath(), sub.getAlias(), sub.getJoinType(), sub.getWithClause()); } totalCriteria.setProjection(impl.getProjection()); totalCriteria.setProjection(Projections.rowCount()); return ((Number)totalCriteria.uniqueResult()).intValue(); } }); } return totalCount; }
/** * Apply the OData $inlinecount to the (already filtered) Criteria. Removes * $skip and $top and $orderby operations and adds a rowCount projection. * * @param crit * a Criteria object. Should already contain only filters that * affect the row count. * @return the same Criteria that was passed in, with operations added. */ public Criteria applyInlineCount(Criteria crit) { crit.setMaxResults(0); crit.setFirstResult(0); CriteriaImpl impl = (CriteriaImpl) crit; Iterator<OrderEntry> iter = impl.iterateOrderings(); while (iter.hasNext()) { iter.next(); iter.remove(); } crit.setProjection(Projections.rowCount()); return crit; }
protected DetachedCriteria(String entityName) { impl = new CriteriaImpl( entityName, null ); criteria = impl; }
protected DetachedCriteria(String entityName, String alias) { impl = new CriteriaImpl( entityName, alias, null ); criteria = impl; }
protected DetachedCriteria(CriteriaImpl impl, Criteria criteria) { this.impl = impl; this.criteria = criteria; }
public CriteriaImpl getRootCriteria() { return rootCriteria; }
public boolean hasRestriction(String path) { final CriteriaImpl.Subcriteria subcriteria = (CriteriaImpl.Subcriteria) getCriteria( path ); return subcriteria != null && subcriteria.hasRestriction(); }
protected EntityCriteria(String entityName) { impl = new CriteriaImpl(entityName, null); criteria = impl; }
protected EntityCriteria(String entityName, String alias) { impl = new CriteriaImpl(entityName, alias, null); criteria = impl; }
protected EntityCriteria(CriteriaImpl impl, Criteria criteria) { this.impl = impl; this.criteria = criteria; }
CriteriaImpl getCriteriaImpl() { return impl; }
@SuppressWarnings("unchecked") private List<Order> privateGetOrders() throws IllegalAccessException, NoSuchFieldException { CriteriaImpl critImpl = (CriteriaImpl) ReflectHelper.getPrivateFieldValue(DetachedCriteria.class, "impl", this); List<Order> orders = (List<Order>) ReflectHelper.getPrivateFieldValue(CriteriaImpl.class, "orderEntries", critImpl); return orders; }
private DetachedCriteriaHelper(final Criteria criteria) { super((CriteriaImpl) criteria, criteria); }
public static Criteria copyCriteria(Criteria src) { return (CriteriaImpl) Serializers.copyObject((CriteriaImpl) src); }
/** * Retrieve the CriteriaImpl used internally to hold the DetachedCriteria state * * @return The internally maintained CriteriaImpl */ CriteriaImpl getCriteriaImpl() { return impl; }
/** * Constructs a new {@code EnhancedDetachedCriteria} instance. * * @param impl * criteria impl. * @param criteria * criteria. */ protected EnhancedDetachedCriteria(CriteriaImpl impl, Criteria criteria) { super(impl, criteria); }
/** * Copy criteria. * * @param criteria the criteria * @return the criteria */ public static Criteria copyCriteria(Criteria criteria) { shouldNotBeNull(criteria, "criteria"); return (Criteria) SerializeTool.copyObject((CriteriaImpl) criteria); }