Search in sources :

Example 1 with SourcePersistentEntity

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

the class MongoRawQueryMethodMatcher method buildRawQuery.

private void buildRawQuery(@NonNull MethodMatchContext matchContext, MethodMatchInfo methodMatchInfo, ParameterElement entityParameter, ParameterElement entitiesParameter, DataMethod.OperationType operationType) {
    MethodElement methodElement = matchContext.getMethodElement();
    List<ParameterElement> parameters = Arrays.asList(matchContext.getParameters());
    ParameterElement entityParam = null;
    SourcePersistentEntity persistentEntity = null;
    if (entityParameter != null) {
        entityParam = entityParameter;
        persistentEntity = matchContext.getEntity(entityParameter.getGenericType());
    } else if (entitiesParameter != null) {
        entityParam = entitiesParameter;
        persistentEntity = matchContext.getEntity(entitiesParameter.getGenericType().getFirstTypeArgument().orElseThrow(IllegalStateException::new));
    }
    QueryResult queryResult;
    if (operationType == DataMethod.OperationType.UPDATE) {
        queryResult = getUpdateQueryResult(matchContext, parameters, entityParam, persistentEntity);
    } else {
        queryResult = getQueryResult(matchContext, parameters, entityParam, persistentEntity);
    }
    boolean encodeEntityParameters = persistentEntity != null || operationType == DataMethod.OperationType.INSERT;
    methodElement.annotate(Query.class, builder -> {
        if (queryResult.getUpdate() != null) {
            builder.member("update", queryResult.getUpdate());
        }
        builder.value(queryResult.getQuery());
    });
    methodMatchInfo.encodeEntityParameters(encodeEntityParameters).queryResult(queryResult).countQueryResult(null);
}
Also used : QueryResult(io.micronaut.data.model.query.builder.QueryResult) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) MethodElement(io.micronaut.inject.ast.MethodElement) ParameterElement(io.micronaut.inject.ast.ParameterElement)

Example 2 with SourcePersistentEntity

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

the class MappedEntityVisitor method visitClass.

@Override
public void visitClass(ClassElement element, VisitorContext context) {
    NamingStrategy namingStrategy = resolveNamingStrategy(element);
    Optional<String> targetName = element.stringValue(MappedEntity.class);
    SourcePersistentEntity entity = entityResolver.apply(element);
    if (isMappedEntity() && !targetName.isPresent()) {
        element.annotate(MappedEntity.class, builder -> {
            String mappedName = namingStrategy.mappedName(entity);
            builder.value(mappedName);
        });
    }
    Map<String, DataType> dataTypes = getConfiguredDataTypes(element);
    Map<String, String> dataConverters = getConfiguredDataConverters(element);
    List<SourcePersistentProperty> properties = entity.getPersistentProperties();
    final List<AnnotationValue<Index>> indexes = properties.stream().filter(x -> ((PersistentProperty) x).findAnnotation(Indexes.class).isPresent()).map(prop -> prop.findAnnotation(Index.class)).flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
    if (!indexes.isEmpty()) {
        element.annotate(Indexes.class, builder -> builder.values(indexes.toArray(new AnnotationValue[] {})));
    }
    for (PersistentProperty property : properties) {
        computeMappingDefaults(namingStrategy, property, dataTypes, dataConverters, context);
    }
    SourcePersistentProperty identity = entity.getIdentity();
    if (identity != null) {
        computeMappingDefaults(namingStrategy, identity, dataTypes, dataConverters, context);
    }
    SourcePersistentProperty[] compositeIdentities = entity.getCompositeIdentity();
    if (compositeIdentities != null) {
        for (SourcePersistentProperty compositeIdentity : compositeIdentities) {
            computeMappingDefaults(namingStrategy, compositeIdentity, dataTypes, dataConverters, context);
        }
    }
    SourcePersistentProperty version = entity.getVersion();
    if (version != null) {
        computeMappingDefaults(namingStrategy, version, dataTypes, dataConverters, context);
    }
}
Also used : DataType(io.micronaut.data.model.DataType) MappedEntity(io.micronaut.data.annotation.MappedEntity) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) ClassElement(io.micronaut.inject.ast.ClassElement) HashMap(java.util.HashMap) TypeDef(io.micronaut.data.annotation.TypeDef) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Utils.getConfiguredDataTypes(io.micronaut.data.processor.visitors.Utils.getConfiguredDataTypes) Utils.getConfiguredDataConverters(io.micronaut.data.processor.visitors.Utils.getConfiguredDataConverters) TypeElementVisitor(io.micronaut.inject.visitor.TypeElementVisitor) MappedProperty(io.micronaut.data.annotation.MappedProperty) PropertyElement(io.micronaut.inject.ast.PropertyElement) InstantiationUtils(io.micronaut.core.reflect.InstantiationUtils) Map(java.util.Map) TypeUtils(io.micronaut.data.processor.visitors.finders.TypeUtils) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) NamingStrategies(io.micronaut.data.model.naming.NamingStrategies) PersistentProperty(io.micronaut.data.model.PersistentProperty) Property(io.micronaut.context.annotation.Property) Index(io.micronaut.data.annotation.Index) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) Collectors(java.util.stream.Collectors) Indexes(io.micronaut.data.annotation.Indexes) Objects(java.util.Objects) NonNull(io.micronaut.core.annotation.NonNull) VisitorContext(io.micronaut.inject.visitor.VisitorContext) List(java.util.List) Association(io.micronaut.data.model.Association) Stream(java.util.stream.Stream) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Optional(java.util.Optional) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) AttributeConverter(io.micronaut.data.model.runtime.convert.AttributeConverter) Relation(io.micronaut.data.annotation.Relation) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) Index(io.micronaut.data.annotation.Index) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) PersistentProperty(io.micronaut.data.model.PersistentProperty) Indexes(io.micronaut.data.annotation.Indexes) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) DataType(io.micronaut.data.model.DataType) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Stream(java.util.stream.Stream)

Example 3 with SourcePersistentEntity

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

the class RepositoryTypeElementVisitor method visitClass.

@Override
public void visitClass(ClassElement element, VisitorContext context) {
    String interfaceName = element.getName();
    if (failing) {
        return;
    }
    if (visitedRepositories.contains(interfaceName)) {
        // prevent duplicate visits
        currentRepository = null;
        currentClass = null;
        return;
    }
    this.currentClass = element;
    entityResolver = new Function<ClassElement, SourcePersistentEntity>() {

        MappedEntityVisitor mappedEntityVisitor = new MappedEntityVisitor();

        MappedEntityVisitor embeddedMappedEntityVisitor = new MappedEntityVisitor(false);

        @Override
        public SourcePersistentEntity apply(ClassElement classElement) {
            return entityMap.computeIfAbsent(classElement.getName(), s -> {
                if (classElement.hasAnnotation("io.micronaut.data.annotation.Embeddable")) {
                    embeddedMappedEntityVisitor.visitClass(classElement, context);
                } else {
                    mappedEntityVisitor.visitClass(classElement, context);
                }
                return new SourcePersistentEntity(classElement, this);
            });
        }
    };
    if (element.hasDeclaredStereotype(Repository.class)) {
        visitedRepositories.add(interfaceName);
        currentRepository = element;
        queryEncoder = QueryBuilder.newQueryBuilder(element.getAnnotationMetadata());
        this.dataTypes = Utils.getConfiguredDataTypes(currentRepository);
        AnnotationMetadata annotationMetadata = element.getAnnotationMetadata();
        List<AnnotationValue<TypeRole>> roleArray = annotationMetadata.findAnnotation(RepositoryConfiguration.class).map(av -> av.getAnnotations("typeRoles", TypeRole.class)).orElse(Collections.emptyList());
        for (AnnotationValue<TypeRole> parameterRole : roleArray) {
            String role = parameterRole.stringValue("role").orElse(null);
            AnnotationClassValue cv = parameterRole.get("type", AnnotationClassValue.class).orElse(null);
            if (StringUtils.isNotEmpty(role) && cv != null) {
                context.getClassElement(cv.getName()).ifPresent(ce -> typeRoles.put(ce.getName(), role));
            }
        }
        if (element.isAssignable(SPRING_REPO)) {
            context.getClassElement("org.springframework.data.domain.Pageable").ifPresent(ce -> typeRoles.put(ce.getName(), TypeRole.PAGEABLE));
            context.getClassElement("org.springframework.data.domain.Page").ifPresent(ce -> typeRoles.put(ce.getName(), TypeRole.PAGE));
            context.getClassElement("org.springframework.data.domain.Slice").ifPresent(ce -> typeRoles.put(ce.getName(), TypeRole.SLICE));
            context.getClassElement("org.springframework.data.domain.Sort").ifPresent(ce -> typeRoles.put(ce.getName(), TypeRole.SORT));
        }
        if (queryEncoder == null) {
            context.fail("QueryEncoder not present on annotation processor path", element);
            failing = true;
        }
    }
}
Also used : DataType(io.micronaut.data.model.DataType) OrderUtil(io.micronaut.core.order.OrderUtil) Arrays(java.util.Arrays) TypeRole(io.micronaut.data.annotation.TypeRole) Internal(io.micronaut.core.annotation.Internal) DataMethod(io.micronaut.data.intercept.annotation.DataMethod) SoftServiceLoader(io.micronaut.core.io.service.SoftServiceLoader) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) Map(java.util.Map) QueryResult(io.micronaut.data.model.query.builder.QueryResult) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) PersistentProperty(io.micronaut.data.model.PersistentProperty) SourceParameterExpressionImpl(io.micronaut.data.processor.model.criteria.impl.SourceParameterExpressionImpl) Sort(io.micronaut.data.model.Sort) Query(io.micronaut.data.annotation.Query) Set(java.util.Set) Collectors(java.util.stream.Collectors) GenericRepository(io.micronaut.data.repository.GenericRepository) StringUtils(io.micronaut.core.util.StringUtils) List(java.util.List) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) MethodElement(io.micronaut.inject.ast.MethodElement) MethodMatchInfo(io.micronaut.data.processor.visitors.finders.MethodMatchInfo) QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) Parameter(io.micronaut.context.annotation.Parameter) RepositoryConfiguration(io.micronaut.data.annotation.RepositoryConfiguration) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) ClassElement(io.micronaut.inject.ast.ClassElement) HashMap(java.util.HashMap) Function(java.util.function.Function) ParameterElement(io.micronaut.inject.ast.ParameterElement) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TypeElementVisitor(io.micronaut.inject.visitor.TypeElementVisitor) TypedElement(io.micronaut.inject.ast.TypedElement) Nullable(io.micronaut.core.annotation.Nullable) MethodMatcher(io.micronaut.data.processor.visitors.finders.MethodMatcher) Page(io.micronaut.data.model.Page) Pageable(io.micronaut.data.model.Pageable) TypeUtils(io.micronaut.data.processor.visitors.finders.TypeUtils) Element(io.micronaut.inject.ast.Element) Iterator(java.util.Iterator) Slice(io.micronaut.data.model.Slice) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) NonNull(io.micronaut.core.annotation.NonNull) BindingParameter(io.micronaut.data.model.query.BindingParameter) VisitorContext(io.micronaut.inject.visitor.VisitorContext) AnnotationValueBuilder(io.micronaut.core.annotation.AnnotationValueBuilder) PersistentEntity(io.micronaut.data.model.PersistentEntity) CollectionUtils(io.micronaut.core.util.CollectionUtils) QueryBuilder(io.micronaut.data.model.query.builder.QueryBuilder) Repository(io.micronaut.data.annotation.Repository) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) DataMethodQueryParameter(io.micronaut.data.intercept.annotation.DataMethodQueryParameter) Collections(java.util.Collections) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) ClassElement(io.micronaut.inject.ast.ClassElement) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) TypeRole(io.micronaut.data.annotation.TypeRole)

Example 4 with SourcePersistentEntity

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

the class RepositoryTypeElementVisitor method processMethodInfo.

private void processMethodInfo(MethodMatchContext methodMatchContext, MethodMatchInfo methodInfo) {
    QueryBuilder queryEncoder = methodMatchContext.getQueryBuilder();
    MethodElement element = methodMatchContext.getMethodElement();
    SourcePersistentEntity entity = methodMatchContext.getRootEntity();
    ParameterElement[] parameters = methodMatchContext.getParameters();
    // populate parameter roles
    for (Map.Entry<String, Element> entry : methodMatchContext.getParametersInRole().entrySet()) {
        methodInfo.addParameterRole(entry.getKey(), entry.getValue().getName());
    }
    List<QueryParameterBinding> parameterBinding = null;
    boolean encodeEntityParameters = false;
    boolean supportsImplicitQueries = methodMatchContext.supportsImplicitQueries();
    QueryResult queryResult = methodInfo.getQueryResult();
    if (queryResult != null) {
        if (methodInfo.isRawQuery()) {
            // no need to annotation since already annotated, just replace the
            // the computed parameter names
            parameterBinding = queryResult.getParameterBindings();
            element.annotate(Query.class, (builder) -> builder.member(DataMethod.META_MEMBER_RAW_QUERY, element.stringValue(Query.class).map(q -> addRawQueryParameterPlaceholders(queryEncoder, queryResult.getQuery(), queryResult.getQueryParts())).orElse(null)));
            ClassElement genericReturnType = methodMatchContext.getReturnType();
            if (methodMatchContext.isTypeInRole(genericReturnType, TypeRole.PAGE) || element.isPresent(Query.class, "countQuery")) {
                QueryResult countQueryResult = methodInfo.getCountQueryResult();
                if (countQueryResult == null) {
                    throw new MatchFailedException("Query returns a Page and does not specify a 'countQuery' member.", element);
                } else {
                    element.annotate(Query.class, (builder) -> builder.member(DataMethod.META_MEMBER_RAW_COUNT_QUERY, addRawQueryParameterPlaceholders(queryEncoder, countQueryResult.getQuery(), countQueryResult.getQueryParts())));
                }
            }
            encodeEntityParameters = methodInfo.isEncodeEntityParameters();
        } else {
            encodeEntityParameters = methodInfo.isEncodeEntityParameters();
            parameterBinding = queryResult.getParameterBindings();
            bindAdditionalParameters(methodMatchContext, entity, parameterBinding, parameters, queryResult.getAdditionalRequiredParameters());
            QueryResult preparedCount = methodInfo.getCountQueryResult();
            if (preparedCount != null) {
                element.annotate(Query.class, annotationBuilder -> {
                    annotationBuilder.value(queryResult.getQuery());
                    annotationBuilder.member(DataMethod.META_MEMBER_COUNT_QUERY, preparedCount.getQuery());
                });
            } else {
                element.annotate(Query.class, annotationBuilder -> {
                    annotationBuilder.value(queryResult.getQuery());
                    String update = queryResult.getUpdate();
                    if (StringUtils.isNotEmpty(update)) {
                        annotationBuilder.member("update", update);
                    }
                });
            }
        }
    }
    ClassElement runtimeInterceptor = methodInfo.getRuntimeInterceptor();
    if (runtimeInterceptor == null) {
        throw new MatchFailedException("Unable to implement Repository method: " + currentRepository.getSimpleName() + "." + element.getName() + "(..). No possible runtime implementations found.", element);
    }
    boolean finalEncodeEntityParameters = encodeEntityParameters;
    List<QueryParameterBinding> finalParameterBinding = parameterBinding;
    element.annotate(DataMethod.class, annotationBuilder -> {
        annotationBuilder.member(DataMethod.META_MEMBER_OPERATION_TYPE, methodInfo.getOperationType());
        annotationBuilder.member(DataMethod.META_MEMBER_ROOT_ENTITY, new AnnotationClassValue<>(entity.getName()));
        // include the roles
        methodInfo.getParameterRoles().forEach(annotationBuilder::member);
        if (methodInfo.isDto()) {
            annotationBuilder.member(DataMethod.META_MEMBER_DTO, true);
        }
        if (methodInfo.isOptimisticLock()) {
            annotationBuilder.member(DataMethod.META_MEMBER_OPTIMISTIC_LOCK, true);
        }
        TypedElement resultType = methodInfo.getResultType();
        if (resultType != null) {
            annotationBuilder.member(DataMethod.META_MEMBER_RESULT_TYPE, new AnnotationClassValue<>(resultType.getName()));
            ClassElement type = resultType.getType();
            if (!TypeUtils.isVoid(type)) {
                annotationBuilder.member(DataMethod.META_MEMBER_RESULT_DATA_TYPE, TypeUtils.resolveDataType(type, dataTypes));
            }
        }
        String idType = resolveIdType(entity);
        if (idType != null) {
            annotationBuilder.member(DataMethod.META_MEMBER_ID_TYPE, idType);
        }
        annotationBuilder.member(DataMethod.META_MEMBER_INTERCEPTOR, new AnnotationClassValue<>(runtimeInterceptor.getName()));
        if (queryResult != null) {
            if (finalParameterBinding.stream().anyMatch(QueryParameterBinding::isExpandable)) {
                annotationBuilder.member(DataMethod.META_MEMBER_EXPANDABLE_QUERY, queryResult.getQueryParts().toArray(new String[0]));
                QueryResult preparedCount = methodInfo.getCountQueryResult();
                if (preparedCount != null) {
                    annotationBuilder.member(DataMethod.META_MEMBER_EXPANDABLE_COUNT_QUERY, preparedCount.getQueryParts().toArray(new String[0]));
                }
            }
            int max = queryResult.getMax();
            if (max > -1) {
                annotationBuilder.member(DataMethod.META_MEMBER_PAGE_SIZE, max);
            }
            long offset = queryResult.getOffset();
            if (offset > 0) {
                annotationBuilder.member(DataMethod.META_MEMBER_PAGE_INDEX, offset);
            }
        }
        Arrays.stream(parameters).filter(p -> p.getGenericType().isAssignable(entity.getName())).findFirst().ifPresent(parameterElement -> annotationBuilder.member(DataMethod.META_MEMBER_ENTITY, parameterElement.getName()));
        if (CollectionUtils.isNotEmpty(finalParameterBinding)) {
            bindParameters(supportsImplicitQueries, finalParameterBinding, finalEncodeEntityParameters, annotationBuilder);
        }
    });
}
Also used : DataType(io.micronaut.data.model.DataType) OrderUtil(io.micronaut.core.order.OrderUtil) Arrays(java.util.Arrays) TypeRole(io.micronaut.data.annotation.TypeRole) Internal(io.micronaut.core.annotation.Internal) DataMethod(io.micronaut.data.intercept.annotation.DataMethod) SoftServiceLoader(io.micronaut.core.io.service.SoftServiceLoader) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) Map(java.util.Map) QueryResult(io.micronaut.data.model.query.builder.QueryResult) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) PersistentProperty(io.micronaut.data.model.PersistentProperty) SourceParameterExpressionImpl(io.micronaut.data.processor.model.criteria.impl.SourceParameterExpressionImpl) Sort(io.micronaut.data.model.Sort) Query(io.micronaut.data.annotation.Query) Set(java.util.Set) Collectors(java.util.stream.Collectors) GenericRepository(io.micronaut.data.repository.GenericRepository) StringUtils(io.micronaut.core.util.StringUtils) List(java.util.List) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) MethodElement(io.micronaut.inject.ast.MethodElement) MethodMatchInfo(io.micronaut.data.processor.visitors.finders.MethodMatchInfo) QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) Parameter(io.micronaut.context.annotation.Parameter) RepositoryConfiguration(io.micronaut.data.annotation.RepositoryConfiguration) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) ClassElement(io.micronaut.inject.ast.ClassElement) HashMap(java.util.HashMap) Function(java.util.function.Function) ParameterElement(io.micronaut.inject.ast.ParameterElement) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TypeElementVisitor(io.micronaut.inject.visitor.TypeElementVisitor) TypedElement(io.micronaut.inject.ast.TypedElement) Nullable(io.micronaut.core.annotation.Nullable) MethodMatcher(io.micronaut.data.processor.visitors.finders.MethodMatcher) Page(io.micronaut.data.model.Page) Pageable(io.micronaut.data.model.Pageable) TypeUtils(io.micronaut.data.processor.visitors.finders.TypeUtils) Element(io.micronaut.inject.ast.Element) Iterator(java.util.Iterator) Slice(io.micronaut.data.model.Slice) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) NonNull(io.micronaut.core.annotation.NonNull) BindingParameter(io.micronaut.data.model.query.BindingParameter) VisitorContext(io.micronaut.inject.visitor.VisitorContext) AnnotationValueBuilder(io.micronaut.core.annotation.AnnotationValueBuilder) PersistentEntity(io.micronaut.data.model.PersistentEntity) CollectionUtils(io.micronaut.core.util.CollectionUtils) QueryBuilder(io.micronaut.data.model.query.builder.QueryBuilder) Repository(io.micronaut.data.annotation.Repository) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) DataMethodQueryParameter(io.micronaut.data.intercept.annotation.DataMethodQueryParameter) Collections(java.util.Collections) QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) Query(io.micronaut.data.annotation.Query) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) MethodElement(io.micronaut.inject.ast.MethodElement) ClassElement(io.micronaut.inject.ast.ClassElement) ParameterElement(io.micronaut.inject.ast.ParameterElement) TypedElement(io.micronaut.inject.ast.TypedElement) Element(io.micronaut.inject.ast.Element) TypedElement(io.micronaut.inject.ast.TypedElement) MethodElement(io.micronaut.inject.ast.MethodElement) ClassElement(io.micronaut.inject.ast.ClassElement) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) QueryBuilder(io.micronaut.data.model.query.builder.QueryBuilder) QueryResult(io.micronaut.data.model.query.builder.QueryResult) ParameterElement(io.micronaut.inject.ast.ParameterElement) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with SourcePersistentEntity

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

the class UpdateMethodMatcher method batchUpdate.

private UpdateCriteriaMethodMatch batchUpdate(java.util.regex.Matcher matcher, ParameterElement idParameter) {
    return new UpdateCriteriaMethodMatch(matcher) {

        @Override
        protected <T> void applyPredicates(String querySequence, ParameterElement[] parameters, PersistentEntityRoot<T> root, PersistentEntityCriteriaUpdate<T> query, SourcePersistentEntityCriteriaBuilder cb) {
            super.applyPredicates(querySequence, parameters, root, query, cb);
            ParameterElement versionParameter = Arrays.stream(parameters).filter(p -> p.hasAnnotation(Version.class)).findFirst().orElse(null);
            Predicate predicate;
            if (versionParameter != null) {
                predicate = cb.and(cb.equal(root.id(), cb.parameter(idParameter)), cb.equal(root.version(), cb.parameter(versionParameter)));
            } else {
                predicate = cb.equal(root.id(), cb.parameter(idParameter));
            }
            query.where(predicate);
        }

        @Override
        protected <T> void applyPredicates(List<ParameterElement> parameters, PersistentEntityRoot<T> root, PersistentEntityCriteriaUpdate<T> query, SourcePersistentEntityCriteriaBuilder cb) {
            ParameterElement versionParameter = parameters.stream().filter(p -> p.hasAnnotation(Version.class)).findFirst().orElse(null);
            Predicate predicate;
            if (versionParameter != null) {
                predicate = cb.and(cb.equal(root.id(), cb.parameter(idParameter)), cb.equal(root.version(), cb.parameter(versionParameter)));
            } else {
                predicate = cb.equal(root.id(), cb.parameter(idParameter));
            }
            query.where(predicate);
        }

        @Override
        protected <T> void addPropertiesToUpdate(MethodMatchContext matchContext, PersistentEntityRoot<T> root, PersistentEntityCriteriaUpdate<T> query, SourcePersistentEntityCriteriaBuilder cb) {
            List<ParameterElement> parameters = matchContext.getParametersNotInRole();
            List<ParameterElement> remainingParameters = parameters.stream().filter(p -> !p.hasAnnotation(Id.class) && !p.hasAnnotation(Version.class)).collect(Collectors.toList());
            ParameterElement idParameter = parameters.stream().filter(p -> p.hasAnnotation(Id.class)).findFirst().orElse(null);
            if (idParameter == null) {
                throw new MatchFailedException("ID required for update method, but not specified");
            }
            SourcePersistentEntity entity = (SourcePersistentEntity) root.getPersistentEntity();
            // Validate @IdClass for composite entity
            if (entity.hasIdentity()) {
                SourcePersistentProperty identity = entity.getIdentity();
                String idType = TypeUtils.getTypeName(identity.getType());
                String idParameterType = TypeUtils.getTypeName(idParameter.getType());
                if (!idType.equals(idParameterType)) {
                    throw new MatchFailedException("ID type of method [" + idParameterType + "] does not match ID type of entity: " + idType);
                }
            } else {
                throw new MatchFailedException("Cannot update by ID for entity that has no ID");
            }
            for (ParameterElement parameter : remainingParameters) {
                String name = getParameterName(parameter);
                SourcePersistentProperty prop = entity.getPropertyByName(name);
                if (prop == null) {
                    throw new MatchFailedException("Cannot update non-existent property: " + name);
                } else {
                    if (prop.isGenerated()) {
                        throw new MatchFailedException("Cannot update a generated property: " + name);
                    } else {
                        query.set(name, cb.parameter(parameter));
                    }
                }
            }
        }
    };
}
Also used : SourcePersistentEntityCriteriaBuilder(io.micronaut.data.processor.model.criteria.SourcePersistentEntityCriteriaBuilder) Arrays(java.util.Arrays) Parameter(io.micronaut.context.annotation.Parameter) MappedEntity(io.micronaut.data.annotation.MappedEntity) ParameterExpression(jakarta.persistence.criteria.ParameterExpression) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) ClassElement(io.micronaut.inject.ast.ClassElement) Internal(io.micronaut.core.annotation.Internal) AbstractPersistentEntityCriteriaUpdate(io.micronaut.data.model.jpa.criteria.impl.AbstractPersistentEntityCriteriaUpdate) DataInterceptor(io.micronaut.data.intercept.DataInterceptor) ParameterElement(io.micronaut.inject.ast.ParameterElement) Version(io.micronaut.data.annotation.Version) Map(java.util.Map) Id(io.micronaut.data.annotation.Id) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) UpdateCriteriaMethodMatch(io.micronaut.data.processor.visitors.finders.criteria.UpdateCriteriaMethodMatch) MatchFailedException(io.micronaut.data.processor.visitors.MatchFailedException) Predicate(jakarta.persistence.criteria.Predicate) AutoPopulated(io.micronaut.data.annotation.AutoPopulated) Set(java.util.Set) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) Collectors(java.util.stream.Collectors) PersistentEntityCriteriaUpdate(io.micronaut.data.model.jpa.criteria.PersistentEntityCriteriaUpdate) PersistentEntityRoot(io.micronaut.data.model.jpa.criteria.PersistentEntityRoot) List(java.util.List) Association(io.micronaut.data.model.Association) Stream(java.util.stream.Stream) MethodMatchContext(io.micronaut.data.processor.visitors.MethodMatchContext) MethodElement(io.micronaut.inject.ast.MethodElement) MatchFailedException(io.micronaut.data.processor.visitors.MatchFailedException) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) Predicate(jakarta.persistence.criteria.Predicate) SourcePersistentEntityCriteriaBuilder(io.micronaut.data.processor.model.criteria.SourcePersistentEntityCriteriaBuilder) MethodMatchContext(io.micronaut.data.processor.visitors.MethodMatchContext) PersistentEntityRoot(io.micronaut.data.model.jpa.criteria.PersistentEntityRoot) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) AbstractPersistentEntityCriteriaUpdate(io.micronaut.data.model.jpa.criteria.impl.AbstractPersistentEntityCriteriaUpdate) PersistentEntityCriteriaUpdate(io.micronaut.data.model.jpa.criteria.PersistentEntityCriteriaUpdate) Version(io.micronaut.data.annotation.Version) UpdateCriteriaMethodMatch(io.micronaut.data.processor.visitors.finders.criteria.UpdateCriteriaMethodMatch) List(java.util.List) ParameterElement(io.micronaut.inject.ast.ParameterElement) Id(io.micronaut.data.annotation.Id)

Aggregations

SourcePersistentEntity (io.micronaut.data.processor.model.SourcePersistentEntity)16 ClassElement (io.micronaut.inject.ast.ClassElement)13 ParameterElement (io.micronaut.inject.ast.ParameterElement)13 List (java.util.List)12 Map (java.util.Map)12 MethodElement (io.micronaut.inject.ast.MethodElement)11 Parameter (io.micronaut.context.annotation.Parameter)10 SourcePersistentProperty (io.micronaut.data.processor.model.SourcePersistentProperty)10 NonNull (io.micronaut.core.annotation.NonNull)9 QueryResult (io.micronaut.data.model.query.builder.QueryResult)9 Arrays (java.util.Arrays)9 Collectors (java.util.stream.Collectors)9 Internal (io.micronaut.core.annotation.Internal)8 DataMethod (io.micronaut.data.intercept.annotation.DataMethod)8 PersistentPropertyPath (io.micronaut.data.model.PersistentPropertyPath)8 TypeUtils (io.micronaut.data.processor.visitors.finders.TypeUtils)8 ArrayList (java.util.ArrayList)8 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)7 MappedEntity (io.micronaut.data.annotation.MappedEntity)7 Query (io.micronaut.data.annotation.Query)7