Java Code Examples for javax.persistence.criteria.CriteriaBuilder#desc()

The following examples show how to use javax.persistence.criteria.CriteriaBuilder#desc() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CriteriaBuilderTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据条件组织一个排序的语句
 * @param <T>
 * @param <T_>
 * @param cb
 * @param root
 * @param cls_
 * @param fieldName
 * @param orderType
 * @return
 */
public static <T extends JpaObject, T_ extends SliceJpaObject_>Order getOrder( CriteriaBuilder cb, Root<T> root, Class<T_> cls_, String fieldName, String orderType ) {
	Boolean fieldExists = false;
	Field[] fields = cls_.getDeclaredFields();
	for( Field field : fields ) {
		if( field.getName().equalsIgnoreCase( fieldName ) ) {
			fieldName = field.getName(); //校正排序列的名称
			fieldExists = true;
		}
	}
	if( !fieldExists ) { //如果排序列不存在,就直接返回空,不排序,让SQL可以正常执行
		return null;
	}		
	if( "desc".equalsIgnoreCase( orderType )) {
		return cb.desc( root.get( fieldName ).as(String.class) );
	}else {
		return cb.asc( root.get( fieldName ).as(String.class) );
	}
}
 
Example 2
Source File: JPACriteriaQueryVisitor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public CriteriaQuery<E> orderBy(List<SingularAttribute<T, ?>> attributes, boolean asc) {
    CriteriaBuilder cb = getCriteriaBuilder();

    List<Order> orders = new ArrayList<>();
    for (SingularAttribute<T, ?> attribute : attributes) {
        Path<?> selection = getRoot().get(attribute);
        Order order = asc ? cb.asc(selection) : cb.desc(selection);
        orders.add(order);
    }
    return getCriteriaQuery().orderBy(orders);
}
 
Example 3
Source File: JpaDao.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Get JPA Order from a page order for a CriteriaQuery
 * @param page request page
 * @param criteria CriteriaQuery to apply Order on.
 * @return new Order
 */
private Order getOrder(Page<?> page, CriteriaQuery<?> criteria) {
	CriteriaBuilder cb = em.getCriteriaBuilder();
	Root<T> root = JpaUtils.findRoot(criteria, getEntityClass());
	String propertyPath = page.getSortName();

	if (log.isDebugEnabled())
		log.debug("Setting order as: " + propertyPath);

	Path<?> path = JpaUtils.getPath(root, propertyPath);

	return page.getOrder() == Page.Order.ASC ? cb.asc(path) : cb.desc(path);
}
 
Example 4
Source File: RepositoryDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
@Override
public ListRepositoriesRequest.Response listRepositories(
    ListRepositoriesRequest request, UserInfo currentLoginUserInfo) throws ModelDBException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    List<String> accessibleResourceIds =
        roleService.getAccessibleResourceIds(
            null,
            new CollaboratorUser(authService, currentLoginUserInfo),
            RepositoryVisibility.PRIVATE,
            ModelDBServiceResourceTypes.REPOSITORY,
            Collections.emptyList());

    if (accessibleResourceIds.isEmpty() && roleService.IsImplemented()) {
      LOGGER.debug("Accessible Repository Ids not found, size 0");
      return ListRepositoriesRequest.Response.newBuilder().setTotalRecords(0).build();
    }

    CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    // Using FROM and JOIN
    CriteriaQuery<RepositoryEntity> criteriaQuery =
        criteriaBuilder.createQuery(RepositoryEntity.class);
    Root<RepositoryEntity> repositoryEntityRoot = criteriaQuery.from(RepositoryEntity.class);
    repositoryEntityRoot.alias(SHORT_NAME);
    List<Predicate> finalPredicatesList = new ArrayList<>();

    if (!request.getWorkspaceName().isEmpty()) {
      WorkspaceDTO workspaceDTO =
          verifyAndGetWorkspaceDTO(
              RepositoryIdentification.newBuilder()
                  .setNamedId(
                      RepositoryNamedIdentification.newBuilder()
                          .setWorkspaceName(request.getWorkspaceName()))
                  .build(),
              false);
      List<KeyValueQuery> workspacePredicates =
          ModelDBUtils.getKeyValueQueriesByWorkspaceDTO(workspaceDTO);
      if (workspacePredicates.size() > 0) {
        Predicate privateWorkspacePredicate =
            criteriaBuilder.equal(
                repositoryEntityRoot.get(ModelDBConstants.WORKSPACE_ID),
                workspacePredicates.get(0).getValue().getStringValue());
        Predicate privateWorkspaceTypePredicate =
            criteriaBuilder.equal(
                repositoryEntityRoot.get(ModelDBConstants.WORKSPACE_TYPE),
                workspacePredicates.get(1).getValue().getNumberValue());
        Predicate privatePredicate =
            criteriaBuilder.and(privateWorkspacePredicate, privateWorkspaceTypePredicate);

        finalPredicatesList.add(privatePredicate);
      }
    }

    if (!accessibleResourceIds.isEmpty()) {
      Expression<String> exp = repositoryEntityRoot.get(ModelDBConstants.ID);
      Predicate predicate2 = exp.in(accessibleResourceIds);
      finalPredicatesList.add(predicate2);
    }

    finalPredicatesList.add(
        criteriaBuilder.equal(repositoryEntityRoot.get(ModelDBConstants.DELETED), false));

    Order orderBy = criteriaBuilder.desc(repositoryEntityRoot.get(ModelDBConstants.DATE_UPDATED));

    Predicate[] predicateArr = new Predicate[finalPredicatesList.size()];
    for (int index = 0; index < finalPredicatesList.size(); index++) {
      predicateArr[index] = finalPredicatesList.get(index);
    }

    Predicate predicateWhereCause = criteriaBuilder.and(predicateArr);
    criteriaQuery.select(repositoryEntityRoot);
    criteriaQuery.where(predicateWhereCause);
    criteriaQuery.orderBy(orderBy);

    Query query = session.createQuery(criteriaQuery);
    LOGGER.debug("Repository final query : {}", query.getQueryString());

    if (request.hasPagination()) {
      // Calculate number of documents to skip
      int pageLimit = request.getPagination().getPageLimit();
      query.setFirstResult((request.getPagination().getPageNumber() - 1) * pageLimit);
      query.setMaxResults(pageLimit);
    }

    List<RepositoryEntity> repositoryEntities = query.list();
    ListRepositoriesRequest.Response.Builder builder =
        ListRepositoriesRequest.Response.newBuilder();

    repositoryEntities.forEach(
        repositoryEntity -> builder.addRepositories(repositoryEntity.toProto()));

    long totalRecords = RdbmsUtils.count(session, repositoryEntityRoot, criteriaQuery);
    builder.setTotalRecords(totalRecords);
    return builder.build();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return listRepositories(request, currentLoginUserInfo);
    } else {
      throw ex;
    }
  }
}
 
Example 5
Source File: ExpectedPartitionValueDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public ExpectedPartitionValueEntity getExpectedPartitionValue(ExpectedPartitionValueKey expectedPartitionValueKey, int offset)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ExpectedPartitionValueEntity> criteria = builder.createQuery(ExpectedPartitionValueEntity.class);

    // The criteria root is the expected partition value.
    Root<ExpectedPartitionValueEntity> expectedPartitionValueEntity = criteria.from(ExpectedPartitionValueEntity.class);

    // Join to the other tables we can filter on.
    Join<ExpectedPartitionValueEntity, PartitionKeyGroupEntity> partitionKeyGroupEntity =
        expectedPartitionValueEntity.join(ExpectedPartitionValueEntity_.partitionKeyGroup);

    // Add a restriction to filter case insensitive groups that match the user specified group.
    Predicate whereRestriction = builder.equal(builder.upper(partitionKeyGroupEntity.get(PartitionKeyGroupEntity_.partitionKeyGroupName)),
        expectedPartitionValueKey.getPartitionKeyGroupName().toUpperCase());

    // Depending on the offset, we might need to order the records in the query.
    Order orderByExpectedPartitionValue = null;

    // Add additional restrictions to handle expected partition value and an optional offset.
    if (offset == 0)
    {
        // Since there is no offset, we need to match the expected partition value exactly.
        whereRestriction = builder.and(whereRestriction, builder
            .equal(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue), expectedPartitionValueKey.getExpectedPartitionValue()));
    }
    else if (offset > 0)
    {
        // For a positive offset value, add a restriction to filter expected partition values that are >= the user specified expected partition value.
        whereRestriction = builder.and(whereRestriction, builder
            .greaterThanOrEqualTo(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                expectedPartitionValueKey.getExpectedPartitionValue()));

        // Order by expected partition value in ascending order.
        orderByExpectedPartitionValue = builder.asc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));
    }
    else
    {
        // For a negative offset value, add a restriction to filter expected partition values that are <= the user specified expected partition value.
        whereRestriction = builder.and(whereRestriction, builder
            .lessThanOrEqualTo(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                expectedPartitionValueKey.getExpectedPartitionValue()));

        // Order by expected partition value in descending order.
        orderByExpectedPartitionValue = builder.desc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));
    }

    // Add the clauses for the query and execute the query.
    if (offset == 0)
    {
        criteria.select(expectedPartitionValueEntity).where(whereRestriction);

        return executeSingleResultQuery(criteria, String
            .format("Found more than one expected partition value with parameters {partitionKeyGroupName=\"%s\", expectedPartitionValue=\"%s\"}.",
                expectedPartitionValueKey.getPartitionKeyGroupName(), expectedPartitionValueKey.getExpectedPartitionValue()));
    }
    else
    {
        criteria.select(expectedPartitionValueEntity).where(whereRestriction).orderBy(orderByExpectedPartitionValue);

        List<ExpectedPartitionValueEntity> resultList =
            entityManager.createQuery(criteria).setFirstResult(Math.abs(offset)).setMaxResults(1).getResultList();

        return resultList.size() > 0 ? resultList.get(0) : null;
    }
}
 
Example 6
Source File: ResourceDao.java    From osiam with MIT License 4 votes vote down vote up
public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count,
        int startIndex,
        String sortBy, String sortOrder, FilterParser<T> filterParser) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<T> resourceQuery = cb.createQuery(clazz);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class);
    Root<T> internalIdRoot = internalIdQuery.from(clazz);
    internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId));

    if (filterTree != null && filterTree.getChildCount() > 0) {
        Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot);
        internalIdQuery.where(predicate);
    }

    resourceQuery.select(resourceRoot).where(
            cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible
    Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id);

    if (sortBy != null && !sortBy.isEmpty()) {
        sortByField = filterParser.createSortByField(sortBy, resourceRoot);
    }

    // default order is ascending
    Order order = cb.asc(sortByField);

    if (sortOrder.equalsIgnoreCase("descending")) {
        order = cb.desc(sortByField);
    }

    resourceQuery.orderBy(order);

    TypedQuery<T> query = em.createQuery(resourceQuery);
    query.setFirstResult(startIndex);
    query.setMaxResults(count);

    List<T> results = query.getResultList();

    long totalResult = getTotalResults(clazz, internalIdQuery);

    return new SearchResult<>(results, totalResult);
}
 
Example 7
Source File: SortField.java    From activejpa with Apache License 2.0 4 votes vote down vote up
protected <T extends Model> Order getOrder(CriteriaBuilder builder, Root<T> root) {
	Path<?> path = getPath(root, name);
	return asc ? builder.asc(path) : builder.desc(path);
}