Search in sources :

Example 11 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class RepositoryJpaCustomImplMetadata method buildQuery.

/**
 * Builds the search query
 *
 * @param bodyBuilder method body builder
 * @param entityVariable name of the variable that contains the Q entity
 * @param globalSearch global search variable name
 * @param referencedFieldParamName
 * @param referencedField
 * @param referencedFieldIdentifierPathName
 * @param formBeanType the JavaType which contains the fields to use for filtering.
 *            Can be null in findAll queries.
 * @param formBeanParameterName the name of the search param
 * @param returnType
 * @param finderName the name of the finder. Only available when method is a
 *            projection/DTO finder.
 * @param partTree
 */
private void buildQuery(InvocableMemberBodyBuilder bodyBuilder, String entityVariable, JavaSymbolName globalSearch, JavaSymbolName referencedFieldParamName, FieldMetadata referencedField, String referencedFieldIdentifierPathName, JavaType formBeanType, String formBeanParameterName, JavaType returnType, JavaSymbolName finderName, PartTree partTree) {
    // Prepare leftJoin for compositions oneToOne
    StringBuilder fetchJoins = new StringBuilder();
    for (RelationInfo relationInfo : entityMetadata.getRelationInfos().values()) {
        if (relationInfo.type == JpaRelationType.COMPOSITION && relationInfo.cardinality == Cardinality.ONE_TO_ONE) {
            fetchJoins.append(".leftJoin(");
            fetchJoins.append(entityVariable);
            fetchJoins.append(".");
            fetchJoins.append(relationInfo.fieldName);
            fetchJoins.append(")");
        }
    }
    // JPQLQuery query = from(qEntity);
    bodyBuilder.appendFormalLine(String.format("%s query = from(%s)%s;", getNameOfJavaType(getJPQLQueryFor(entity)), entityVariable, fetchJoins));
    bodyBuilder.newLine();
    if (formBeanType != null) {
        // Query for finder
        // if (formSearch != null) {
        bodyBuilder.appendFormalLine(String.format("if (%s != null) {", formBeanParameterName));
        if (partTree != null) {
            buildFormBeanFilterBody(bodyBuilder, formBeanType, formBeanParameterName, entityVariable, partTree);
        } else {
            // formBean is an entity, filter by all its fields
            for (Entry<String, FieldMetadata> field : this.typesFieldsMetadata.get(formBeanType).entrySet()) {
                // if (formSearch.getField() != null) {
                String accessorMethodName = BeanInfoUtils.getAccessorMethodName(field.getValue()).getSymbolName();
                bodyBuilder.appendIndent();
                bodyBuilder.appendFormalLine(String.format("if (%s.%s() != null) {", formBeanParameterName, accessorMethodName));
                // Get path field name from field mappings
                String pathFieldName = getValueOfPairFor(this.typesFieldMaps.get(formBeanType), field.getKey());
                // query.where(myEntity.field.eq(formBean.getField()));
                bodyBuilder.appendIndent();
                bodyBuilder.appendIndent();
                bodyBuilder.appendFormalLine(String.format("query.where(%s.eq(%s.%s()));", pathFieldName, formBeanParameterName, accessorMethodName));
                // }
                bodyBuilder.appendIndent();
                bodyBuilder.appendFormalLine("}");
            }
        }
        // }
        bodyBuilder.appendFormalLine("}");
        bodyBuilder.newLine();
    } else if (referencedFieldParamName != null && referencedFieldIdentifierPathName != null) {
        // Query for reference
        // Assert.notNull(referenced, "referenced is required");
        bodyBuilder.appendFormalLine(String.format("%s.notNull(%s, \"%s is required\");", SpringJavaType.ASSERT.getNameIncludingTypeParameters(false, importResolver), referencedFieldParamName, referencedFieldParamName));
        bodyBuilder.newLine();
        // Query should include a where clause
        if (referencedField.getAnnotation(JpaJavaType.MANY_TO_MANY) != null) {
            // query.where(referencedFieldPath.contains(referencedFieldName));
            bodyBuilder.appendFormalLine(String.format("query.where(%s.contains(%s));", referencedFieldIdentifierPathName, referencedFieldParamName));
        } else {
            // query.where(referencedFieldPath.eq(referencedFieldName));
            bodyBuilder.appendFormalLine(String.format("query.where(%s.eq(%s));", referencedFieldIdentifierPathName, referencedFieldParamName));
        }
    }
    // Path<?>[] paths = new Path[] { .... };
    bodyBuilder.appendIndent();
    final String pathType = getNameOfJavaType(QUERYDSL_PATH);
    bodyBuilder.append(String.format("%s<?>[] paths = new %s<?>[] {", pathType, pathType));
    List<String> toAppend = new ArrayList<String>();
    // ... returnType.field1, returnType.field2);
    if (!this.typesAreProjections.get(returnType)) {
        // Return type is the same entity
        Map<String, FieldMetadata> projectionFields = this.typesFieldsMetadata.get(returnType);
        Iterator<Entry<String, FieldMetadata>> iterator = projectionFields.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, FieldMetadata> field = iterator.next();
            String fieldName = field.getValue().getFieldName().getSymbolName();
            toAppend.add(entityVariable + "." + fieldName);
        }
    } else {
        // Return type is a projection
        List<Pair<String, String>> projectionFields = this.typesFieldMaps.get(returnType);
        Validate.notNull(projectionFields, "Couldn't get projection fields for %s", this.defaultReturnType);
        Iterator<Pair<String, String>> iterator = projectionFields.iterator();
        while (iterator.hasNext()) {
            Entry<String, String> entry = iterator.next();
            toAppend.add(entry.getValue());
        }
    }
    bodyBuilder.append(StringUtils.join(toAppend, ','));
    bodyBuilder.append("};");
    bodyBuilder.newLine();
    // applyGlobalSearch(search, query, paths);
    bodyBuilder.appendFormalLine("applyGlobalSearch(globalSearch, query, paths);");
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ToStringBuilder(org.apache.commons.lang3.builder.ToStringBuilder) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) Pair(org.apache.commons.lang3.tuple.Pair)

Example 12 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class ServiceImplMetadata method builSaveMethodBody.

/**
 * Build "save" method body which delegates on repository
 *
 * @param methodToBeImplemented
 * @param isBatch
 * @param isDelete
 * @return
 */
private InvocableMemberBodyBuilder builSaveMethodBody(final MethodMetadata methodToBeImplemented) {
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    final JavaSymbolName param0 = methodToBeImplemented.getParameterNames().get(0);
    /*
     * // Ensure the relationships are maintained
     * entity.addToRelatedEntity(entity.getRelatedEntity());
     */
    boolean commentAdded = false;
    Map<String, RelationInfo> relationInfos = entityMetadata.getRelationInfos();
    for (Entry<String, RelationInfo> entry : relationInfos.entrySet()) {
        RelationInfo info = entry.getValue();
        if (info.cardinality == Cardinality.ONE_TO_ONE) {
            if (!commentAdded) {
                bodyBuilder.newLine();
                bodyBuilder.appendFormalLine("// Ensure the relationships are maintained");
                commentAdded = true;
            }
            bodyBuilder.appendFormalLine("%s.%s(%s.get%s());", param0, info.addMethod.getMethodName(), param0, StringUtils.capitalize(entry.getKey()));
            bodyBuilder.newLine();
        }
    }
    bodyBuilder.appendFormalLine("%s %s().%s(%s);", methodToBeImplemented.getReturnType().equals(JavaType.VOID_PRIMITIVE) ? "" : "return", getAccessorMethod(repositoryFieldMetadata).getMethodName(), methodToBeImplemented.getMethodName().getSymbolName(), param0);
    return bodyBuilder;
}
Also used : JavaSymbolName(org.springframework.roo.model.JavaSymbolName) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)

Example 13 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class RepositoryJpaCustomMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    final RepositoryJpaCustomAnnotationValues annotationValues = new RepositoryJpaCustomAnnotationValues(governorPhysicalTypeMetadata);
    // Getting repository custom
    JavaType entity = annotationValues.getEntity();
    Validate.notNull(entity, "ERROR: Repository custom interface should be contain an entity on @RooJpaRepositoryCustom annotation");
    final ClassOrInterfaceTypeDetails repositoryClass = getRepositoryJpaLocator().getRepository(entity);
    final String repositoryMedatadataId = RepositoryJpaMetadata.createIdentifier(repositoryClass);
    registerDependency(repositoryMedatadataId, metadataIdentificationString);
    RepositoryJpaMetadata repositoryMetadata = getMetadataService().get(repositoryMedatadataId);
    // This metadata is not available yet.
    if (repositoryMetadata == null) {
        return null;
    }
    // Add dependency between modules
    ClassOrInterfaceTypeDetails cid = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
    String module = cid.getName().getModule();
    getTypeLocationService().addModuleDependency(module, entity);
    getTypeLocationService().addModuleDependency(module, repositoryMetadata.getDefaultReturnType());
    // Get field which entity is field part
    List<Pair<FieldMetadata, RelationInfo>> relationsAsChild = getJpaOperations().getFieldChildPartOfRelation(entity);
    for (Pair<FieldMetadata, RelationInfo> fieldInfo : relationsAsChild) {
        // Add dependency between modules
        getTypeLocationService().addModuleDependency(module, fieldInfo.getLeft().getFieldType());
    }
    // Register dependency between JavaBeanMetadata and this one
    final ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
    final String javaBeanMetadataKey = JavaBeanMetadata.createIdentifier(entityDetails);
    registerDependency(javaBeanMetadataKey, metadataIdentificationString);
    String entityMetadataKey = JpaEntityMetadata.createIdentifier(entityDetails);
    JpaEntityMetadata entityMetadata = getMetadataService().get(entityMetadataKey);
    // Entity metadata is not available
    if (entityMetadata == null) {
        return null;
    }
    return new RepositoryJpaCustomMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, annotationValues, entityMetadata.getCurrentIndentifierField().getFieldType(), entity, repositoryMetadata, relationsAsChild);
}
Also used : RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) Pair(org.apache.commons.lang3.tuple.Pair)

Example 14 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class JpaDataOnDemandCreator method getEntityAndRelatedEntitiesList.

/**
 * Searches the related entities of provided entity and returns a
 * {@link List} with all the related entities plus the provided entity.
 *
 * @param entity
 *            the entity JavaType to search for its related entities.
 * @return a List with all the related entities.
 */
private List<JavaType> getEntityAndRelatedEntitiesList(JavaType entity) {
    ClassOrInterfaceTypeDetails entityDetails = getEntityDetails(entity);
    JpaEntityMetadata entityMetadata = metadataService.get(JpaEntityMetadata.createIdentifier(entityDetails));
    List<JavaType> entitiesToCreateFactories = new ArrayList<JavaType>();
    entitiesToCreateFactories.add(entity);
    // Get related child entities
    for (RelationInfo info : entityMetadata.getRelationInfos().values()) {
        // Add to list
        if (!entitiesToCreateFactories.contains(info.childType)) {
            entitiesToCreateFactories.add(info.childType);
        }
    }
    return entitiesToCreateFactories;
}
Also used : RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) ArrayList(java.util.ArrayList) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata)

Example 15 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class JpaOperationsImpl method getFieldChildPartOfRelation.

@Override
public List<Pair<FieldMetadata, RelationInfo>> getFieldChildPartOfRelation(ClassOrInterfaceTypeDetails entityCdi) {
    JavaType domainType = entityCdi.getType();
    JpaEntityMetadata entityMetadata = getJpaEntityMetadata(entityCdi);
    Validate.notNull(entityMetadata, "%s should be a Jpa Entity", domainType);
    Map<String, FieldMetadata> relations = entityMetadata.getRelationsAsChild();
    List<Pair<FieldMetadata, RelationInfo>> childRelations = new ArrayList<Pair<FieldMetadata, RelationInfo>>();
    JpaEntityMetadata parent;
    JavaType parentType;
    RelationInfo info;
    for (Entry<String, FieldMetadata> fieldEntry : relations.entrySet()) {
        parentType = fieldEntry.getValue().getFieldType().getBaseType();
        parent = getJpaEntityMetadata(parentType);
        Validate.notNull(parent, "Can't get information about Entity %s which is declared as parent in %s.%s field", parentType, domainType, fieldEntry.getKey());
        info = parent.getRelationInfosByMappedBy(domainType, fieldEntry.getKey());
        if (info != null) {
            childRelations.add(Pair.of(fieldEntry.getValue(), info));
        }
    }
    return childRelations;
}
Also used : JdkJavaType(org.springframework.roo.model.JdkJavaType) RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) ArrayList(java.util.ArrayList) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

RelationInfo (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo)31 ArrayList (java.util.ArrayList)27 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)19 JpaEntityMetadata (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata)18 JavaType (org.springframework.roo.model.JavaType)18 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)17 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)16 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)15 InvocableMemberBodyBuilder (org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)14 MethodMetadataBuilder (org.springframework.roo.classpath.details.MethodMetadataBuilder)12 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)12 ServiceMetadata (org.springframework.roo.addon.layers.service.addon.ServiceMetadata)11 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)11 RooJavaType (org.springframework.roo.model.RooJavaType)11 Pair (org.apache.commons.lang3.tuple.Pair)8 JdkJavaType (org.springframework.roo.model.JdkJavaType)8 SpringJavaType (org.springframework.roo.model.SpringJavaType)8 Jsr303JavaType (org.springframework.roo.model.Jsr303JavaType)5 SpringletsJavaType (org.springframework.roo.model.SpringletsJavaType)5 HashMap (java.util.HashMap)4