private void buildOrderClause( StringBuilder queryStringBuilder, QueryModel queryModel, Criteria criteria, CriteriaQueryTranslator criteriaQueryTranslator) { boolean firstOrderItem = true; if (queryModel.getSorts() != null) { for (Sort sort : queryModel.getSorts()) { if (firstOrderItem) { queryStringBuilder.append(" order by "); } else { queryStringBuilder.append(','); } Order order = sort.getSortDirection() == SortDirection.Ascending ? Order.asc(sort.getField()) : Order.desc(sort.getField()); queryStringBuilder.append(order.toSqlString(criteria, criteriaQueryTranslator)); firstOrderItem = false; } } }
@Override public Iterable<T> findUsingQueryModel(QueryModel queryModel) { if (accessControlContextProvider == null || roleAllowsAccess(queryModel.getAccessControlContext().getRole())) { Criteria criteria = buildCriteria(queryModel); if (queryModel.getSorts() != null) { for (Sort sort : queryModel.getSorts()) { criteria.addOrder( sort.getSortDirection() == SortDirection.Ascending ? Order.asc(sort.getField()) : Order.desc(sort.getField())); } } if (queryModel.getMaxResults() > 0) { criteria.setMaxResults(queryModel.getMaxResults()); } if (queryModel.getFirstResult() > 0) { criteria.setFirstResult(queryModel.getFirstResult()); } //noinspection unchecked return criteria.list(); } else { //noinspection unchecked return createEntryBasedQuery(queryModel).list(); } }
// TODO: Add projection, maxResults, firstResult support private Query createEntryBasedQuery(QueryModel queryModel) { Criteria criteria = getCurrentSession().createCriteria(persistentClass); for (String associationPath : queryModel.getAssociationConditions().keySet()) { criteria.createCriteria(associationPath); } CriteriaQueryTranslator criteriaQueryTranslator = new CriteriaQueryTranslator( (SessionFactoryImplementor) sessionFactory, (CriteriaImpl) criteria, persistentClass.getName(), CriteriaQueryTranslator.ROOT_SQL_ALIAS); StringBuilder queryStringBuilder = new StringBuilder(); buildSelectClause( queryStringBuilder, criteriaQueryTranslator, queryModel.getAssociationConditions().keySet()); List<TypedValue> parameters = buildWhereClause(queryStringBuilder, queryModel, criteria, criteriaQueryTranslator); if ((queryModel.getAssociationConditions() == null || queryModel.getAssociationConditions().isEmpty()) && (queryModel.getSorts() == null || queryModel.getSorts().isEmpty())) { buildDefaultOrderClause(queryStringBuilder); } else { // can't use the default ordering by "ace.id" because of "select distinct..." syntax buildOrderClause(queryStringBuilder, queryModel, criteria, criteriaQueryTranslator); } Query query = getCurrentSession().createQuery(queryStringBuilder.toString()); setParameters(parameters, query, queryModel.getAccessControlContext()); return query; }