Search in sources :

Example 1 with Pageable

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

the class AbstractSpecificationInterceptor method preparedQueryForCriteria.

protected final <E, QR> PreparedQuery<E, QR> preparedQueryForCriteria(RepositoryMethodKey methodKey, MethodInvocationContext<T, R> context, Type type) {
    Class<Object> rootEntity = getRequiredRootEntity(context);
    Pageable pageable = Pageable.UNPAGED;
    for (Object param : context.getParameterValues()) {
        if (param instanceof Pageable) {
            pageable = (Pageable) param;
            break;
        }
    }
    QueryBuilder sqlQueryBuilder = sqlQueryBuilderForRepositories.computeIfAbsent(methodKey, repositoryMethodKey -> {
        Class<QueryBuilder> builder = context.getAnnotationMetadata().classValue(RepositoryConfiguration.class, "queryBuilder").orElseThrow(() -> new IllegalStateException("Cannot determine QueryBuilder"));
        BeanIntrospection<QueryBuilder> introspection = BeanIntrospection.getIntrospection(builder);
        if (introspection.getConstructorArguments().length == 1 && introspection.getConstructorArguments()[0].getType() == AnnotationMetadata.class) {
            return introspection.instantiate(context.getAnnotationMetadata());
        }
        return introspection.instantiate();
    });
    QueryResult queryResult;
    if (type == Type.COUNT || type == Type.FIND_ALL || type == Type.FIND_ONE || type == Type.FIND_PAGE) {
        QuerySpecification<Object> specification = getQuerySpecification(context);
        PersistentEntityCriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
        Root<Object> root = criteriaQuery.from(rootEntity);
        if (specification != null) {
            Predicate predicate = specification.toPredicate(root, criteriaQuery, criteriaBuilder);
            if (predicate != null) {
                criteriaQuery.where(predicate);
            }
        }
        if (type == Type.FIND_ALL) {
            for (Object param : context.getParameterValues()) {
                if (param instanceof Sort && param != pageable) {
                    Sort sort = (Sort) param;
                    if (sort.isSorted()) {
                        criteriaQuery.orderBy(getOrders(sort, root, criteriaBuilder));
                        break;
                    }
                }
            }
        } else if (type == Type.COUNT) {
            criteriaQuery.select(criteriaBuilder.count(root));
        }
        queryResult = ((QueryResultPersistentEntityCriteriaQuery) criteriaQuery).buildQuery(sqlQueryBuilder);
    } else if (type == Type.DELETE_ALL) {
        DeleteSpecification<Object> specification = getDeleteSpecification(context);
        PersistentEntityCriteriaDelete<Object> criteriaDelete = criteriaBuilder.createCriteriaDelete(rootEntity);
        Root<Object> root = criteriaDelete.from(rootEntity);
        if (specification != null) {
            Predicate predicate = specification.toPredicate(root, criteriaDelete, criteriaBuilder);
            if (predicate != null) {
                criteriaDelete.where(predicate);
            }
        }
        queryResult = ((QueryResultPersistentEntityCriteriaQuery) criteriaDelete).buildQuery(sqlQueryBuilder);
    } else if (type == Type.UPDATE_ALL) {
        UpdateSpecification<Object> specification = getUpdateSpecification(context);
        PersistentEntityCriteriaUpdate<Object> criteriaUpdate = criteriaBuilder.createCriteriaUpdate(rootEntity);
        Root<Object> root = criteriaUpdate.from(rootEntity);
        if (specification != null) {
            Predicate predicate = specification.toPredicate(root, criteriaUpdate, criteriaBuilder);
            if (predicate != null) {
                criteriaUpdate.where(predicate);
            }
        }
        queryResult = ((QueryResultPersistentEntityCriteriaQuery) criteriaUpdate).buildQuery(sqlQueryBuilder);
    } else {
        throw new IllegalStateException("Unknown criteria type: " + type);
    }
    String query = queryResult.getQuery();
    String update = queryResult.getUpdate();
    List<io.micronaut.data.model.query.builder.QueryParameterBinding> parameterBindings = queryResult.getParameterBindings();
    List<QueryParameterBinding> queryParameters = new ArrayList<>(parameterBindings.size());
    for (io.micronaut.data.model.query.builder.QueryParameterBinding p : parameterBindings) {
        queryParameters.add(new QueryResultParameterBinding(p, queryParameters));
    }
    String[] queryParts = queryParameters.stream().anyMatch(QueryParameterBinding::isExpandable) ? queryResult.getQueryParts().toArray(new String[0]) : null;
    StoredQuery<E, QR> storedQuery;
    if (type == Type.COUNT) {
        storedQuery = (StoredQuery<E, QR>) storedQueryResolver.createCountStoredQuery(context.getExecutableMethod(), DataMethod.OperationType.COUNT, context.getName(), context.getAnnotationMetadata(), rootEntity, query, queryParts, queryParameters);
    } else if (type == Type.FIND_ALL) {
        storedQuery = storedQueryResolver.createStoredQuery(context.getExecutableMethod(), DataMethod.OperationType.QUERY, context.getName(), context.getAnnotationMetadata(), rootEntity, query, null, queryParts, queryParameters, !pageable.isUnpaged(), false);
    } else {
        DataMethod.OperationType operationType;
        switch(type) {
            case COUNT:
                operationType = DataMethod.OperationType.COUNT;
                break;
            case DELETE_ALL:
                operationType = DataMethod.OperationType.DELETE;
                break;
            case UPDATE_ALL:
                operationType = DataMethod.OperationType.UPDATE;
                break;
            case FIND_ALL:
            case FIND_ONE:
            case FIND_PAGE:
                operationType = DataMethod.OperationType.QUERY;
                break;
            default:
                throw new IllegalStateException("Unknown value: " + type);
        }
        storedQuery = storedQueryResolver.createStoredQuery(context.getExecutableMethod(), operationType, context.getName(), context.getAnnotationMetadata(), rootEntity, query, update, queryParts, queryParameters, false, true);
    }
    return preparedQueryResolver.resolveQuery(context, storedQuery, pageable);
}
Also used : QueryParameterBinding(io.micronaut.data.model.runtime.QueryParameterBinding) DeleteSpecification(io.micronaut.data.repository.jpa.criteria.DeleteSpecification) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) ArrayList(java.util.ArrayList) QueryBuilder(io.micronaut.data.model.query.builder.QueryBuilder) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Predicate(jakarta.persistence.criteria.Predicate) QueryResult(io.micronaut.data.model.query.builder.QueryResult) Pageable(io.micronaut.data.model.Pageable) Sort(io.micronaut.data.model.Sort) RepositoryConfiguration(io.micronaut.data.annotation.RepositoryConfiguration) Root(jakarta.persistence.criteria.Root) QueryResultPersistentEntityCriteriaQuery(io.micronaut.data.model.jpa.criteria.impl.QueryResultPersistentEntityCriteriaQuery) PersistentEntityCriteriaDelete(io.micronaut.data.model.jpa.criteria.PersistentEntityCriteriaDelete)

Example 2 with Pageable

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

the class HibernateJpaOperations method findStream.

@NonNull
@Override
public <T, R> Stream<R> findStream(@NonNull PreparedQuery<T, R> preparedQuery) {
    // noinspection ConstantConditions
    return transactionOperations.executeRead(status -> {
        String query = preparedQuery.getQuery();
        Pageable pageable = preparedQuery.getPageable();
        Session currentSession = getCurrentSession();
        Class<R> resultType = preparedQuery.getResultType();
        boolean isNativeQuery = preparedQuery.isNative();
        if (preparedQuery.isDtoProjection()) {
            Query<Tuple> q;
            if (isNativeQuery) {
                q = currentSession.createNativeQuery(query, Tuple.class);
            } else {
                q = currentSession.createQuery(query, Tuple.class);
            }
            bindParameters(q, preparedQuery, query);
            bindPageable(q, pageable);
            return q.stream().map(tuple -> (new BeanIntrospectionMapper<Tuple, R>() {

                @Override
                public Object read(Tuple tuple1, String alias) {
                    return tuple1.get(alias);
                }

                @Override
                public ConversionService<?> getConversionService() {
                    return dataConversionService;
                }
            }).map(tuple, resultType));
        } else {
            Query<R> q;
            @SuppressWarnings("unchecked") Class<R> wrapperType = ReflectionUtils.getWrapperType(resultType);
            if (isNativeQuery) {
                Class<T> rootEntity = preparedQuery.getRootEntity();
                if (wrapperType != rootEntity) {
                    NativeQuery<Tuple> nativeQuery = currentSession.createNativeQuery(query, Tuple.class);
                    bindParameters(nativeQuery, preparedQuery, query);
                    bindPageable(nativeQuery, pageable);
                    return nativeQuery.stream().map(tuple -> {
                        Object o = tuple.get(0);
                        if (wrapperType.isInstance(o)) {
                            return (R) o;
                        } else {
                            return dataConversionService.convertRequired(o, wrapperType);
                        }
                    });
                } else {
                    q = currentSession.createNativeQuery(query, wrapperType);
                }
            } else {
                q = currentSession.createQuery(query, wrapperType);
            }
            bindParameters(q, preparedQuery, query);
            bindPageable(q, pageable);
            return q.stream();
        }
    });
}
Also used : Pageable(io.micronaut.data.model.Pageable) ConversionService(io.micronaut.core.convert.ConversionService) DataConversionService(io.micronaut.data.runtime.convert.DataConversionService) Tuple(javax.persistence.Tuple) Session(org.hibernate.Session) NonNull(io.micronaut.core.annotation.NonNull)

Example 3 with Pageable

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

the class HibernateJpaOperations method count.

@Override
public <T> long count(PagedQuery<T> pagedQuery) {
    return transactionOperations.executeRead(status -> {
        Session session = getCurrentSession();
        CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
        CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
        Root<T> root = query.from(pagedQuery.getRootEntity());
        query = query.select(criteriaBuilder.count(root));
        Query<Long> q = session.createQuery(query);
        Pageable pageable = pagedQuery.getPageable();
        bindCriteriaSort(query, root, criteriaBuilder, pageable);
        bindPageable(q, pageable);
        bindQueryHints(q, pagedQuery, session);
        return q.getSingleResult();
    });
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Pageable(io.micronaut.data.model.Pageable) Session(org.hibernate.Session)

Example 4 with Pageable

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

the class HibernateJpaOperations method findPage.

@Override
public <R> Page<R> findPage(@NonNull PagedQuery<R> query) {
    // noinspection ConstantConditions
    return transactionOperations.executeRead(status -> {
        Session session = getCurrentSession();
        CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
        Class<R> entity = query.getRootEntity();
        Pageable pageable = query.getPageable();
        Query<R> q = buildCriteriaQuery(session, entity, criteriaBuilder, pageable);
        List<R> resultList = q.list();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        countQuery.select(criteriaBuilder.count(countQuery.from(entity)));
        Long total = session.createQuery(countQuery).getSingleResult();
        return Page.of(resultList, pageable, total);
    });
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Pageable(io.micronaut.data.model.Pageable) Session(org.hibernate.Session)

Example 5 with Pageable

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

the class DefaultMongoPreparedQuery method getAggregation.

@Override
public MongoAggregation getAggregation() {
    MongoAggregation aggregation = mongoStoredQuery.getAggregation(preparedQuery.getContext());
    Pageable pageable = getPageable();
    if (pageable != Pageable.UNPAGED) {
        List<Bson> pipeline = new ArrayList<>(aggregation.getPipeline());
        applyPageable(pageable, pipeline);
        return new MongoAggregation(pipeline, aggregation.getOptions());
    }
    return aggregation;
}
Also used : Pageable(io.micronaut.data.model.Pageable) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson)

Aggregations

Pageable (io.micronaut.data.model.Pageable)20 Sort (io.micronaut.data.model.Sort)7 ArrayList (java.util.ArrayList)7 List (java.util.List)7 PreparedQuery (io.micronaut.data.model.runtime.PreparedQuery)6 Collectors (java.util.stream.Collectors)6 NonNull (io.micronaut.core.annotation.NonNull)5 RuntimePersistentEntity (io.micronaut.data.model.runtime.RuntimePersistentEntity)5 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)4 Internal (io.micronaut.core.annotation.Internal)4 StoredQuery (io.micronaut.data.model.runtime.StoredQuery)4 MongoFindOptions (io.micronaut.data.mongodb.operations.options.MongoFindOptions)4 DataConversionService (io.micronaut.data.runtime.convert.DataConversionService)4 EachBean (io.micronaut.context.annotation.EachBean)3 Parameter (io.micronaut.context.annotation.Parameter)3 Nullable (io.micronaut.core.annotation.Nullable)3 Page (io.micronaut.data.model.Page)3 Bson (org.bson.conversions.Bson)3 Session (org.hibernate.Session)3 BeanProperty (io.micronaut.core.beans.BeanProperty)2