示例#1
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected int countCriteriaResult(final Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List<CriteriaImpl.OrderEntry> orderEntries = null;
    try {
      orderEntries =
          (List<CriteriaImpl.OrderEntry>) ReflectionUtils.getFieldValue(impl, "orderEntries");
      ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
      logger.error("", e);
    }

    int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();

    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);
    }

    return totalCount;
  }
 /**
  * 使用指定查询对象进行分页查询.
  *
  * @param criteria 实体的查询对象
  * @param pageNo 页号,从1开始.
  * @param pageSize 每页中的记录数
  * @return 当前页的分页对象
  */
 public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) {
   CriteriaImpl impl = (CriteriaImpl) criteria;
   // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
   Projection projection = impl.getProjection();
   List<CriteriaImpl.OrderEntry> orderEntries;
   try {
     orderEntries = (List) BeanUtils.getPrivateProperty(impl, "orderEntries");
     BeanUtils.setPrivateProperty(impl, "orderEntries", new ArrayList());
   } catch (Exception e) {
     logger.error(e.getMessage());
     throw new InternalError(" Runtime Exception impossibility throw ");
   }
   // 执行查询
   long totalCount =
       ((Number) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
   // 将之前的Projection和OrderBy条件重新设回去
   criteria.setProjection(projection);
   if (projection == null) {
     criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
   }
   try {
     BeanUtils.setPrivateProperty(impl, "orderEntries", orderEntries);
   } catch (Exception e) {
     logger.error(e.getMessage());
     throw new InternalError(" Runtime Exception impossibility throw ");
   }
   // 返回分页对象
   if (totalCount < 1) return new Page();
   int startIndex = Page.getStartOfPage(pageNo, pageSize);
   List list = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
   return new Page(startIndex, totalCount, pageSize, list);
 }
 public String getGroupBy() {
   if (rootCriteria.getProjection().isGrouped()) {
     return rootCriteria
         .getProjection()
         .toGroupSqlString(rootCriteria.getProjectionCriteria(), this);
   } else {
     return "";
   }
 }
示例#4
0
  /**
   * @param criteria
   * @param pageNo
   * @param pageSize
   * @return
   */
  public PageResult getList(
      final DetachedCriteria detachedCriteria, final int pageNo, final int pageSize) {
    PageResult pager = new PageResult();

    Criteria criteria =
        (Criteria)
            getHibernateTemplate()
                .execute(
                    new HibernateCallback() {
                      public Object doInHibernate(Session session)
                          throws HibernateException, SQLException {
                        Criteria criteria = detachedCriteria.getExecutableCriteria(session);
                        return criteria;
                      }
                    });
    CriteriaImpl impl = (CriteriaImpl) criteria;

    Projection projection = impl.getProjection();

    List orderEntries = null;
    try {
      orderEntries = (List) MyBeanUtils.getFieldValue(impl, "orderEntries");
      MyBeanUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }

    Long iCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
    int totalCount = ((iCount != null) ? iCount.intValue() : 0);
    pager.setTotalRecordCount(totalCount); // 查询总记录数
    criteria.setProjection(projection);
    if (projection == null) {
      criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }

    try {
      List innerOrderEntries = (List) MyBeanUtils.getFieldValue(impl, "orderEntries");
      Iterator it = orderEntries.iterator();
      while (it.hasNext()) {
        innerOrderEntries.add(it.next());
      }
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }

    criteria.setFirstResult(pageSize * (pageNo - 1));
    criteria.setMaxResults(pageSize);
    pager.setPageSize(pageSize);
    pager.setCurrentPageNo(pageNo);
    pager.setResults(criteria.list());
    return pager;
  }
 private void createAliasCriteriaMap() {
   aliasCriteriaMap.put(rootCriteria.getAlias(), rootCriteria);
   Iterator iter = rootCriteria.iterateSubcriteria();
   while (iter.hasNext()) {
     Criteria subcriteria = (Criteria) iter.next();
     if (subcriteria.getAlias() != null) {
       Object old = aliasCriteriaMap.put(subcriteria.getAlias(), subcriteria);
       if (old != null) {
         throw new QueryException("duplicate alias: " + subcriteria.getAlias());
       }
     }
   }
 }
  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];
    }
  }
  /** 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 = 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;
    }
  }
 public String getOrderBy() {
   StringBuffer orderBy = new StringBuffer(30);
   Iterator criterionIterator = rootCriteria.iterateOrderings();
   while (criterionIterator.hasNext()) {
     CriteriaImpl.OrderEntry oe = (CriteriaImpl.OrderEntry) criterionIterator.next();
     orderBy.append(oe.getOrder().toSqlString(oe.getCriteria(), this));
     if (criterionIterator.hasNext()) {
       orderBy.append(", ");
     }
   }
   return orderBy.toString();
 }
 public String getWhereCondition() {
   StringBuffer condition = new StringBuffer(30);
   Iterator criterionIterator = rootCriteria.iterateExpressionEntries();
   while (criterionIterator.hasNext()) {
     CriteriaImpl.CriterionEntry entry = (CriteriaImpl.CriterionEntry) criterionIterator.next();
     String sqlString = entry.getCriterion().toSqlString(entry.getCriteria(), this);
     condition.append(sqlString);
     if (criterionIterator.hasNext()) {
       condition.append(" and ");
     }
   }
   return condition.toString();
 }
  /**
   * 通过count查询获得本次查询所能获得的对象总数.
   *
   * @return page对象中的totalCount属性将赋值.
   */
  protected int countQueryResult(Page<T> page, 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) BeanUtils.getFieldValue(impl, "orderEntries");
      BeanUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
      log.error("不可能抛出的异常", e);
    }

    // 执行Count查询
    int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();
    if (totalCount < 1) return -1;

    // 将之前的Projection和OrderBy条件重新设回去
    c.setProjection(projection);

    if (projection == null) {
      c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }
    if (transformer != null) {
      c.setResultTransformer(transformer);
    }

    try {
      BeanUtils.setFieldValue(impl, "orderEntries", orderEntries);
    } catch (Exception e) {
      log.error("不可能抛出的异常", e);
    }

    return totalCount;
  }
示例#11
0
  protected long countCriteriaResult(Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List orderEntries = null;
    try {
      orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");

      ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
      this.logger.error("不可能抛出的异常:{}", e.getMessage());
    }

    Long totalCountObject = Long.valueOf(0L);
    Object object = c.setProjection(Projections.rowCount()).uniqueResult();
    if (object instanceof Long) totalCountObject = (Long) object;
    else if (object instanceof Integer) {
      totalCountObject = Long.valueOf(((Integer) object).intValue());
    }
    long totalCount = (totalCountObject != null) ? totalCountObject.longValue() : 0L;

    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) {
      this.logger.error("不可能抛出的异常:{}", e.getMessage());
    }

    return totalCount;
  }
 private void createAssociationPathCriteriaMap() {
   Iterator iter = rootCriteria.iterateSubcriteria();
   while (iter.hasNext()) {
     CriteriaImpl.Subcriteria crit = (CriteriaImpl.Subcriteria) iter.next();
     String wholeAssociationPath = getWholeAssociationPath(crit);
     Object old = associationPathCriteriaMap.put(wholeAssociationPath, crit);
     if (old != null) {
       throw new QueryException("duplicate association path: " + wholeAssociationPath);
     }
     int joinType = crit.getJoinType();
     old = associationPathJoinTypesMap.put(wholeAssociationPath, new Integer(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 String getSelect() {
   return rootCriteria.getProjection().toSqlString(rootCriteria.getProjectionCriteria(), 0, this);
 }
 public String[] getProjectedAliases() {
   return rootCriteria.getProjection().getAliases();
 }
 public String[] getProjectedColumnAliases() {
   return rootCriteria.getProjection() instanceof EnhancedProjection
       ? ((EnhancedProjection) rootCriteria.getProjection())
           .getColumnAliases(0, rootCriteria, this)
       : rootCriteria.getProjection().getColumnAliases(0);
 }
 public Type[] getProjectedTypes() {
   return rootCriteria.getProjection().getTypes(rootCriteria, this);
 }
 public boolean hasProjection() {
   return rootCriteria.getProjection() != null;
 }
  public QueryParameters getQueryParameters() {
    LockOptions lockOptions = new LockOptions();
    RowSelection selection = new RowSelection();
    selection.setFirstRow(rootCriteria.getFirstResult());
    selection.setMaxRows(rootCriteria.getMaxResults());
    selection.setTimeout(rootCriteria.getTimeout());
    selection.setFetchSize(rootCriteria.getFetchSize());

    Iterator iter = rootCriteria.getLockModes().entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry me = (Map.Entry) iter.next();
      final Criteria subcriteria = getAliasedCriteria((String) me.getKey());
      lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), (LockMode) me.getValue());
    }
    List values = new ArrayList();
    List types = new ArrayList();
    iter = rootCriteria.iterateSubcriteria();
    while (iter.hasNext()) {
      CriteriaImpl.Subcriteria subcriteria = (CriteriaImpl.Subcriteria) iter.next();
      LockMode lm = subcriteria.getLockMode();
      if (lm != null) {
        lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lm);
      }
      if (subcriteria.getWithClause() != null) {
        TypedValue[] tv = subcriteria.getWithClause().getTypedValues(subcriteria, this);
        for (int i = 0; i < tv.length; i++) {
          values.add(tv[i].getValue());
          types.add(tv[i].getType());
        }
      }
    }

    // Type and value gathering for the WHERE clause needs to come AFTER lock mode gathering,
    // because the lock mode gathering loop now contains join clauses which can contain
    // parameter bindings (as in the HQL WITH clause).
    iter = rootCriteria.iterateExpressionEntries();
    while (iter.hasNext()) {
      CriteriaImpl.CriterionEntry ce = (CriteriaImpl.CriterionEntry) iter.next();
      TypedValue[] tv = ce.getCriterion().getTypedValues(ce.getCriteria(), this);
      for (int i = 0; i < tv.length; i++) {
        values.add(tv[i].getValue());
        types.add(tv[i].getType());
      }
    }

    Object[] valueArray = values.toArray();
    Type[] typeArray = ArrayHelper.toTypeArray(types);
    return new QueryParameters(
        typeArray,
        valueArray,
        lockOptions,
        selection,
        rootCriteria.isReadOnlyInitialized(),
        (rootCriteria.isReadOnlyInitialized() ? rootCriteria.isReadOnly() : false),
        rootCriteria.getCacheable(),
        rootCriteria.getCacheRegion(),
        rootCriteria.getComment(),
        rootCriteria.isLookupByNaturalKey(),
        rootCriteria.getResultTransformer());
  }