Search in sources :

Example 6 with Sort

use of io.micronaut.data.model.Sort in project micronaut-data by micronaut-projects.

the class HibernateJpaOperations method bindCriteriaSort.

private <T> void bindCriteriaSort(CriteriaQuery<T> criteriaQuery, Root<?> root, CriteriaBuilder builder, @NonNull Sort sort) {
    List<Order> orders = new ArrayList<>();
    for (Sort.Order order : sort.getOrderBy()) {
        Path<String> path = root.get(order.getProperty());
        Expression expression = order.isIgnoreCase() ? builder.lower(path) : path;
        switch(order.getDirection()) {
            case DESC:
                orders.add(builder.desc(expression));
                continue;
            default:
            case ASC:
                orders.add(builder.asc(expression));
        }
    }
    criteriaQuery.orderBy(orders);
}
Also used : Order(javax.persistence.criteria.Order) Expression(javax.persistence.criteria.Expression) ArrayList(java.util.ArrayList) Sort(io.micronaut.data.model.Sort)

Example 7 with Sort

use of io.micronaut.data.model.Sort in project micronaut-data by micronaut-projects.

the class FindPageSpecificationInterceptor method intercept.

@Override
public Page intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    if (context.getParameterValues().length != 2) {
        throw new IllegalStateException("Expected exactly 2 arguments to method");
    }
    Specification specification = getSpecification(context);
    final EntityManager entityManager = jpaOperations.getCurrentEntityManager();
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Class<Object> rootEntity = getRequiredRootEntity(context);
    final CriteriaQuery<Object> query = criteriaBuilder.createQuery(rootEntity);
    final Root<Object> root = query.from(rootEntity);
    final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder);
    if (predicate != null) {
        query.where(predicate);
    }
    query.select(root);
    Pageable pageable = getPageable(context);
    final Sort sort = pageable.getSort();
    if (sort.isSorted()) {
        query.orderBy(getOrders(sort, root, criteriaBuilder));
    }
    final TypedQuery<Object> typedQuery = entityManager.createQuery(query);
    if (pageable.isUnpaged()) {
        List<Object> resultList = typedQuery.getResultList();
        return Page.of(resultList, pageable, resultList.size());
    } else {
        typedQuery.setFirstResult((int) pageable.getOffset());
        typedQuery.setMaxResults(pageable.getSize());
        final List<Object> results = typedQuery.getResultList();
        final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        final Root<?> countRoot = countQuery.from(rootEntity);
        final Predicate countPredicate = specification.toPredicate(countRoot, countQuery, criteriaBuilder);
        if (countPredicate != null) {
            countQuery.where(countPredicate);
        }
        countQuery.select(criteriaBuilder.count(countRoot));
        Long singleResult = entityManager.createQuery(countQuery).getSingleResult();
        return Page.of(results, pageable, singleResult);
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Specification(io.micronaut.data.jpa.repository.criteria.Specification) Predicate(javax.persistence.criteria.Predicate) EntityManager(javax.persistence.EntityManager) Pageable(io.micronaut.data.model.Pageable) Sort(io.micronaut.data.model.Sort)

Example 8 with Sort

use of io.micronaut.data.model.Sort in project micronaut-data by micronaut-projects.

the class PageableRequestArgumentBinder method bind.

@Override
public BindingResult<Pageable> bind(ArgumentConversionContext<Pageable> context, HttpRequest<?> source) {
    HttpParameters parameters = source.getParameters();
    int page = Math.max(parameters.getFirst(configuration.getPageParameterName(), Integer.class).orElse(0), 0);
    final int configuredMaxSize = configuration.getMaxPageSize();
    final int defaultSize = configuration.getDefaultPageSize();
    int size = Math.min(parameters.getFirst(configuration.getSizeParameterName(), Integer.class).orElse(defaultSize), configuredMaxSize);
    String sortParameterName = configuration.getSortParameterName();
    boolean hasSort = parameters.contains(sortParameterName);
    Pageable pageable;
    Sort sort = null;
    if (hasSort) {
        List<String> sortParams = parameters.getAll(sortParameterName);
        List<Sort.Order> orders = sortParams.stream().map(sortMapper).collect(Collectors.toList());
        sort = Sort.of(orders);
    }
    if (size < 1) {
        if (page == 0 && configuredMaxSize < 1 && sort == null) {
            pageable = Pageable.UNPAGED;
        } else {
            pageable = Pageable.from(page, defaultSize, sort);
        }
    } else {
        pageable = Pageable.from(page, size, sort);
    }
    return () -> Optional.of(pageable);
}
Also used : Pageable(io.micronaut.data.model.Pageable) HttpParameters(io.micronaut.http.HttpParameters) Sort(io.micronaut.data.model.Sort)

Example 9 with Sort

use of io.micronaut.data.model.Sort in project micronaut-data by micronaut-projects.

the class PreparedQueryDBOperation method sortById.

/**
 * Build a sort for ID for the given entity.
 *
 * @param persistentEntity The entity
 * @param <K>              The entity type
 * @return The sort
 */
@NonNull
private <K> Sort sortById(RuntimePersistentEntity<K> persistentEntity) {
    Sort sort;
    RuntimePersistentProperty<K> identity = persistentEntity.getIdentity();
    if (identity == null) {
        throw new DataAccessException("Pagination requires an entity ID on SQL Server");
    }
    sort = Sort.unsorted().order(Sort.Order.asc(identity.getName()));
    return sort;
}
Also used : Sort(io.micronaut.data.model.Sort) DataAccessException(io.micronaut.data.exceptions.DataAccessException) NonNull(io.micronaut.core.annotation.NonNull)

Example 10 with Sort

use of io.micronaut.data.model.Sort in project micronaut-data by micronaut-projects.

the class MongoQueryBuilder method buildQuery.

@Override
public QueryResult buildQuery(AnnotationMetadata annotationMetadata, QueryModel query) {
    ArgumentUtils.requireNonNull("annotationMetadata", annotationMetadata);
    ArgumentUtils.requireNonNull("query", query);
    QueryState queryState = new QueryState(query, true);
    Map<String, Object> predicateObj = new LinkedHashMap<>();
    Map<String, Object> group = new LinkedHashMap<>();
    Map<String, Object> projectionObj = new LinkedHashMap<>();
    Map<String, Object> countObj = new LinkedHashMap<>();
    addLookups(query.getJoinPaths(), queryState);
    List<Map<String, Object>> pipeline = queryState.rootLookups.pipeline;
    buildProjection(query.getProjections(), query.getPersistentEntity(), group, projectionObj, countObj);
    QueryModel.Junction criteria = query.getCriteria();
    if (!criteria.isEmpty()) {
        predicateObj = buildWhereClause(annotationMetadata, criteria, queryState);
    }
    if (!predicateObj.isEmpty()) {
        pipeline.add(singletonMap("$match", predicateObj));
    }
    if (!group.isEmpty()) {
        group.put("_id", null);
        pipeline.add(singletonMap("$group", group));
    }
    if (!countObj.isEmpty()) {
        pipeline.add(countObj);
    }
    if (!projectionObj.isEmpty()) {
        pipeline.add(singletonMap("$project", projectionObj));
    } else {
        String customProjection = annotationMetadata.stringValue(MongoAnnotations.PROJECTION).orElse(null);
        if (customProjection != null) {
            pipeline.add(singletonMap("$project", new RawJsonValue(customProjection)));
        }
    }
    Sort sort = query.getSort();
    if (sort.isSorted() && !sort.getOrderBy().isEmpty()) {
        Map<String, Object> sortObj = new LinkedHashMap<>();
        sort.getOrderBy().forEach(order -> sortObj.put(order.getProperty(), order.isAscending() ? 1 : -1));
        pipeline.add(singletonMap("$sort", sortObj));
    } else {
        String customSort = annotationMetadata.stringValue(MongoAnnotations.SORT).orElse(null);
        if (customSort != null) {
            pipeline.add(singletonMap("$sort", new RawJsonValue(customSort)));
        }
    }
    if (query.getOffset() > 0) {
        pipeline.add(singletonMap("$skip", query.getOffset()));
    }
    if (query.getMax() != -1) {
        pipeline.add(singletonMap("$limit", query.getMax()));
    }
    String q;
    if (pipeline.isEmpty()) {
        q = "{}";
    } else if (isMatchOnlyStage(pipeline)) {
        q = toJsonString(predicateObj);
    } else {
        q = toJsonString(pipeline);
    }
    return new QueryResult() {

        @NonNull
        @Override
        public String getQuery() {
            return q;
        }

        @Override
        public int getMax() {
            return query.getMax();
        }

        @Override
        public long getOffset() {
            return query.getOffset();
        }

        @Override
        public List<String> getQueryParts() {
            return Collections.emptyList();
        }

        @Override
        public List<QueryParameterBinding> getParameterBindings() {
            return queryState.getParameterBindings();
        }

        @Override
        public Map<String, String> getAdditionalRequiredParameters() {
            return Collections.emptyMap();
        }
    };
}
Also used : QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) QueryModel(io.micronaut.data.model.query.QueryModel) LinkedHashMap(java.util.LinkedHashMap) QueryResult(io.micronaut.data.model.query.builder.QueryResult) Sort(io.micronaut.data.model.Sort) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Collections.singletonMap(java.util.Collections.singletonMap)

Aggregations

Sort (io.micronaut.data.model.Sort)12 Pageable (io.micronaut.data.model.Pageable)7 ArrayList (java.util.ArrayList)5 NonNull (io.micronaut.core.annotation.NonNull)4 PreparedQuery (io.micronaut.data.model.runtime.PreparedQuery)3 RuntimePersistentEntity (io.micronaut.data.model.runtime.RuntimePersistentEntity)3 List (java.util.List)3 Collectors (java.util.stream.Collectors)3 Sorts (com.mongodb.client.model.Sorts)2 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)2 Internal (io.micronaut.core.annotation.Internal)2 PersistentPropertyPath (io.micronaut.data.model.PersistentPropertyPath)2 Map (java.util.Map)2 EntityManager (javax.persistence.EntityManager)2 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)2 Expression (javax.persistence.criteria.Expression)2 Order (javax.persistence.criteria.Order)2 ApplicationContext (io.micronaut.context.ApplicationContext)1 EachBean (io.micronaut.context.annotation.EachBean)1 Parameter (io.micronaut.context.annotation.Parameter)1