Search in sources :

Example 1 with DataConversionService

use of io.micronaut.data.runtime.convert.DataConversionService 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 2 with DataConversionService

use of io.micronaut.data.runtime.convert.DataConversionService in project micronaut-data by micronaut-projects.

the class HibernateJpaOperations method findAll.

@NonNull
@Override
public <T, R> Iterable<R> findAll(@NonNull PreparedQuery<T, R> preparedQuery) {
    return transactionOperations.executeRead(status -> {
        Session entityManager = sessionFactory.getCurrentSession();
        String queryStr = preparedQuery.getQuery();
        Pageable pageable = preparedQuery.getPageable();
        if (pageable != Pageable.UNPAGED) {
            Sort sort = pageable.getSort();
            if (sort.isSorted()) {
                queryStr += QUERY_BUILDER.buildOrderBy(queryStr, getEntity(preparedQuery.getRootEntity()), sort).getQuery();
            }
        }
        if (preparedQuery.isDtoProjection()) {
            Query<Tuple> q;
            if (preparedQuery.isNative()) {
                q = entityManager.createNativeQuery(queryStr, Tuple.class);
            } else if (queryStr.toLowerCase(Locale.ENGLISH).startsWith("select new ")) {
                Class<R> wrapperType = ReflectionUtils.getWrapperType(preparedQuery.getResultType());
                Query<R> query = entityManager.createQuery(queryStr, wrapperType);
                bindPreparedQuery(query, preparedQuery, entityManager, queryStr);
                return query.list();
            } else {
                q = entityManager.createQuery(queryStr, Tuple.class);
            }
            bindPreparedQuery(q, preparedQuery, entityManager, queryStr);
            return q.stream().map(tuple -> {
                Set<String> properties = tuple.getElements().stream().map(TupleElement::getAlias).collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
                return (new BeanIntrospectionMapper<Tuple, R>() {

                    @Override
                    public Object read(Tuple tuple1, String alias) {
                        if (!properties.contains(alias)) {
                            return null;
                        }
                        return tuple1.get(alias);
                    }

                    @Override
                    public ConversionService<?> getConversionService() {
                        return dataConversionService;
                    }
                }).map(tuple, preparedQuery.getResultType());
            }).collect(Collectors.toList());
        } else {
            Class<R> wrapperType = ReflectionUtils.getWrapperType(preparedQuery.getResultType());
            Query<R> q;
            if (preparedQuery.isNative()) {
                if (DataType.ENTITY.equals(preparedQuery.getResultDataType())) {
                    q = entityManager.createNativeQuery(queryStr, wrapperType);
                } else {
                    q = entityManager.createNativeQuery(queryStr);
                }
            } else {
                q = entityManager.createQuery(queryStr, wrapperType);
            }
            bindPreparedQuery(q, preparedQuery, entityManager, queryStr);
            return q.list();
        }
    });
}
Also used : DataType(io.micronaut.data.model.DataType) Connection(java.sql.Connection) ArrayUtils(io.micronaut.core.util.ArrayUtils) ExecutorReactiveOperations(io.micronaut.data.runtime.operations.ExecutorReactiveOperations) SubGraph(org.hibernate.graph.SubGraph) EachBean(io.micronaut.context.annotation.EachBean) StoredQuery(io.micronaut.data.model.runtime.StoredQuery) Locale(java.util.Locale) Map(java.util.Map) Query(org.hibernate.query.Query) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) DeleteOperation(io.micronaut.data.model.runtime.DeleteOperation) TypeHint(io.micronaut.core.annotation.TypeHint) AsyncCapableRepository(io.micronaut.data.operations.async.AsyncCapableRepository) Path(javax.persistence.criteria.Path) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) JpaRepositoryOperations(io.micronaut.data.jpa.operations.JpaRepositoryOperations) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) IntrospectionException(io.micronaut.core.beans.exceptions.IntrospectionException) Graph(org.hibernate.graph.Graph) Sort(io.micronaut.data.model.Sort) RuntimePersistentProperty(io.micronaut.data.model.runtime.RuntimePersistentProperty) Collection(java.util.Collection) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) QueryHint(io.micronaut.data.annotation.QueryHint) PreparedQuery(io.micronaut.data.model.runtime.PreparedQuery) Serializable(java.io.Serializable) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) EntityManagerFactory(javax.persistence.EntityManagerFactory) Order(javax.persistence.criteria.Order) Optional(java.util.Optional) TupleElement(javax.persistence.TupleElement) Named(jakarta.inject.Named) JpaQueryBuilder(io.micronaut.data.model.query.builder.jpa.JpaQueryBuilder) QueryParameterBinding(io.micronaut.data.model.runtime.QueryParameterBinding) AttributeNode(org.hibernate.graph.AttributeNode) RootGraph(org.hibernate.graph.RootGraph) Parameter(io.micronaut.context.annotation.Parameter) TransactionOperations(io.micronaut.transaction.TransactionOperations) Creator(io.micronaut.core.annotation.Creator) BeanProperty(io.micronaut.core.beans.BeanProperty) Session(org.hibernate.Session) FlushModeType(javax.persistence.FlushModeType) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) HibernatePresenceCondition(io.micronaut.jdbc.spring.HibernatePresenceCondition) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ApplicationContext(io.micronaut.context.ApplicationContext) Nullable(io.micronaut.core.annotation.Nullable) NativeQuery(org.hibernate.query.NativeQuery) Page(io.micronaut.data.model.Page) Pageable(io.micronaut.data.model.Pageable) ReactiveCapableRepository(io.micronaut.data.operations.reactive.ReactiveCapableRepository) ExecutorAsyncOperations(io.micronaut.data.runtime.operations.ExecutorAsyncOperations) Argument(io.micronaut.core.type.Argument) Expression(javax.persistence.criteria.Expression) ConversionService(io.micronaut.core.convert.ConversionService) BeanWrapper(io.micronaut.core.beans.BeanWrapper) ReactiveRepositoryOperations(io.micronaut.data.operations.reactive.ReactiveRepositoryOperations) Root(javax.persistence.criteria.Root) ExecutorService(java.util.concurrent.ExecutorService) Tuple(javax.persistence.Tuple) PagedQuery(io.micronaut.data.model.runtime.PagedQuery) Iterator(java.util.Iterator) DataConversionService(io.micronaut.data.runtime.convert.DataConversionService) EntityManager(javax.persistence.EntityManager) InsertBatchOperation(io.micronaut.data.model.runtime.InsertBatchOperation) ReflectionUtils(io.micronaut.core.reflect.ReflectionUtils) NonNull(io.micronaut.core.annotation.NonNull) CollectionUtils(io.micronaut.core.util.CollectionUtils) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) DeleteBatchOperation(io.micronaut.data.model.runtime.DeleteBatchOperation) InsertOperation(io.micronaut.data.model.runtime.InsertOperation) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) EntityGraph(io.micronaut.data.jpa.annotation.EntityGraph) BeanIntrospectionMapper(io.micronaut.data.runtime.mapper.BeanIntrospectionMapper) RuntimePersistentEntity(io.micronaut.data.model.runtime.RuntimePersistentEntity) UpdateBatchOperation(io.micronaut.data.model.runtime.UpdateBatchOperation) UpdateOperation(io.micronaut.data.model.runtime.UpdateOperation) Collections(java.util.Collections) Type(org.hibernate.type.Type) Set(java.util.Set) TreeSet(java.util.TreeSet) StoredQuery(io.micronaut.data.model.runtime.StoredQuery) Query(org.hibernate.query.Query) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) PreparedQuery(io.micronaut.data.model.runtime.PreparedQuery) NativeQuery(org.hibernate.query.NativeQuery) PagedQuery(io.micronaut.data.model.runtime.PagedQuery) Pageable(io.micronaut.data.model.Pageable) TupleElement(javax.persistence.TupleElement) ConversionService(io.micronaut.core.convert.ConversionService) DataConversionService(io.micronaut.data.runtime.convert.DataConversionService) Sort(io.micronaut.data.model.Sort) Tuple(javax.persistence.Tuple) Session(org.hibernate.Session) NonNull(io.micronaut.core.annotation.NonNull)

Aggregations

NonNull (io.micronaut.core.annotation.NonNull)2 ConversionService (io.micronaut.core.convert.ConversionService)2 Pageable (io.micronaut.data.model.Pageable)2 ApplicationContext (io.micronaut.context.ApplicationContext)1 EachBean (io.micronaut.context.annotation.EachBean)1 Parameter (io.micronaut.context.annotation.Parameter)1 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)1 Creator (io.micronaut.core.annotation.Creator)1 Nullable (io.micronaut.core.annotation.Nullable)1 TypeHint (io.micronaut.core.annotation.TypeHint)1 BeanIntrospection (io.micronaut.core.beans.BeanIntrospection)1 BeanProperty (io.micronaut.core.beans.BeanProperty)1 BeanWrapper (io.micronaut.core.beans.BeanWrapper)1 IntrospectionException (io.micronaut.core.beans.exceptions.IntrospectionException)1 ReflectionUtils (io.micronaut.core.reflect.ReflectionUtils)1 Argument (io.micronaut.core.type.Argument)1 ArgumentUtils (io.micronaut.core.util.ArgumentUtils)1 ArrayUtils (io.micronaut.core.util.ArrayUtils)1 CollectionUtils (io.micronaut.core.util.CollectionUtils)1 QueryHint (io.micronaut.data.annotation.QueryHint)1