Search in sources :

Example 1 with ClassAccessor

use of org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor in project eclipselink by eclipse-ee4j.

the class MetadataProject method processSequencingAccessors.

/**
 * INTERNAL:
 * Process the sequencing information. At this point, through validation, it
 * is not possible to have:
 *   1 - a table generator with the generator name equal to
 *       DEFAULT_SEQUENCE_GENERATOR or DEFAULT_IDENTITY_GENERATOR
 *   2 - a sequence generator with the name eqaul to DEFAULT_TABLE_GENERATOR
 *       or DEFAULT_IDENTITY_GENERATOR
 *   3 - you can't have both a sequence generator and a table generator with
 *       the same DEFAULT_AUTO_GENERATOR name.
 *
 * @see addTableGenerator and addSequenceGenerator.
 */
protected void processSequencingAccessors() {
    if (!m_generatedValues.isEmpty()) {
        // 1 - Build our map of sequences keyed on generator names.
        Hashtable<String, Sequence> sequences = new Hashtable<String, Sequence>();
        for (SequenceGeneratorMetadata sequenceGenerator : m_sequenceGenerators.values()) {
            sequences.put(sequenceGenerator.getName(), sequenceGenerator.process(m_logger));
        }
        for (UuidGeneratorMetadata uuidGenerator : m_uuidGenerators.values()) {
            sequences.put(uuidGenerator.getName(), uuidGenerator.process(m_logger));
        }
        for (TableGeneratorMetadata tableGenerator : m_tableGenerators.values()) {
            sequences.put(tableGenerator.getGeneratorName(), tableGenerator.process(m_logger));
        }
        // create them using the Table and Sequence generator metadata.
        if (!sequences.containsKey(DEFAULT_TABLE_GENERATOR)) {
            TableGeneratorMetadata tableGenerator = new TableGeneratorMetadata(DEFAULT_TABLE_GENERATOR);
            // This code was attempting to use the platform default sequence name,
            // however the platform has not been set yet, so it would never work,
            // it was also causing the platform default sequence to be set, causing the DatabasePlatform default to be used,
            // so I am removing this code, as it breaks the platform default sequence and does not work.
            // Sequence seq = m_session.getDatasourcePlatform().getDefaultSequence();
            // Using "" as the default should make the platform default it.
            String defaultTableGeneratorName = "";
            // Process the default values.
            processTable(tableGenerator, defaultTableGeneratorName, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema(), tableGenerator);
            sequences.put(DEFAULT_TABLE_GENERATOR, tableGenerator.process(m_logger));
        }
        if (!sequences.containsKey(DEFAULT_SEQUENCE_GENERATOR)) {
            sequences.put(DEFAULT_SEQUENCE_GENERATOR, new SequenceGeneratorMetadata(DEFAULT_SEQUENCE_GENERATOR, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema()).process(m_logger));
        }
        if (!sequences.containsKey(DEFAULT_IDENTITY_GENERATOR)) {
            sequences.put(DEFAULT_IDENTITY_GENERATOR, new SequenceGeneratorMetadata(DEFAULT_IDENTITY_GENERATOR, 1, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema(), true).process(m_logger));
        }
        if (!sequences.containsKey(DEFAULT_UUID_GENERATOR)) {
            sequences.put(DEFAULT_UUID_GENERATOR, new UuidGeneratorMetadata().process(m_logger));
        }
        // Use a temporary sequence generator to build a qualifier to set on
        // the default generator. Don't use this generator as the default
        // auto generator though.
        SequenceGeneratorMetadata tempGenerator = new SequenceGeneratorMetadata(DEFAULT_AUTO_GENERATOR, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema());
        DatasourceLogin login = m_session.getProject().getLogin();
        login.setTableQualifier(tempGenerator.processQualifier());
        // 3 - Loop through generated values and set sequences for each.
        for (MetadataClass entityClass : m_generatedValues.keySet()) {
            // Skip setting sequences if our accessor is null, must be a mapped superclass
            ClassAccessor accessor = m_allAccessors.get(entityClass.getName());
            if (accessor != null) {
                m_generatedValues.get(entityClass).process(accessor.getDescriptor(), sequences, login);
            }
        }
    }
}
Also used : DatasourceLogin(org.eclipse.persistence.sessions.DatasourceLogin) SequenceGeneratorMetadata(org.eclipse.persistence.internal.jpa.metadata.sequencing.SequenceGeneratorMetadata) UuidGeneratorMetadata(org.eclipse.persistence.internal.jpa.metadata.sequencing.UuidGeneratorMetadata) MetadataClass(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass) ClassAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor) Hashtable(java.util.Hashtable) TableGeneratorMetadata(org.eclipse.persistence.internal.jpa.metadata.sequencing.TableGeneratorMetadata) Sequence(org.eclipse.persistence.sequencing.Sequence)

Example 2 with ClassAccessor

use of org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor in project eclipselink by eclipse-ee4j.

the class CanonicalModelProcessor method generateCanonicalModelClass.

/**
 * INTERNAL:
 */
protected void generateCanonicalModelClass(MetadataClass metadataClass, Element element, PersistenceUnit persistenceUnit) throws IOException {
    Writer writer = null;
    try {
        ClassAccessor accessor = persistenceUnit.getClassAccessor(metadataClass);
        String qualifiedName = accessor.getAccessibleObjectName();
        String className = getName(qualifiedName);
        String classPackage = getPackage(qualifiedName);
        String qualifiedCanonicalName = persistenceUnit.getQualifiedCanonicalName(qualifiedName);
        String canonicalName = getName(qualifiedCanonicalName);
        String canonicalpackage = getPackage(qualifiedCanonicalName);
        boolean isNewJava = SourceVersion.RELEASE_8.compareTo(processingEnv.getSourceVersion()) < 0;
        JavaFileObject file = processingEnv.getFiler().createSourceFile(qualifiedCanonicalName, element);
        writer = file.openWriter();
        // Print the package if we have one.
        if (!canonicalpackage.equals("")) {
            writer.append("package " + canonicalpackage + ";\n\n");
        }
        // Go through the accessor list, ignoring any transient accessors
        // to build our attributes and import list.
        ArrayList<String> attributes = new ArrayList<>();
        HashMap<String, String> imports = new HashMap<>();
        if (generateGenerated) {
            if (isNewJava) {
                imports.put("Generated", "javax.annotation.processing.Generated");
            } else {
                imports.put("Generated", "jakarta.annotation.Generated");
            }
        }
        // Import the model class if the canonical class is generated elsewhere.
        if (!classPackage.equals(canonicalpackage)) {
            imports.put(className, qualifiedName);
        }
        for (MappingAccessor mappingAccessor : accessor.getDescriptor().getMappingAccessors()) {
            if (!mappingAccessor.isTransient()) {
                MetadataAnnotatedElement annotatedElement = mappingAccessor.getAnnotatedElement();
                // Must go through the mapping accessor for the raw class
                // since it may be a virtual mapping accessor with an
                // attribute type.
                MetadataClass rawClass = mappingAccessor.getRawClass();
                // NOTE: order of checking is important.
                String attributeType;
                String types = className;
                if (mappingAccessor.isBasic()) {
                    types = types + ", " + getUnqualifiedType(getBoxedType(annotatedElement, rawClass), imports);
                    attributeType = AttributeType.SingularAttribute.name();
                    imports.put(attributeType, "jakarta.persistence.metamodel.SingularAttribute");
                } else {
                    if (rawClass.isList()) {
                        attributeType = AttributeType.ListAttribute.name();
                        imports.put(attributeType, "jakarta.persistence.metamodel.ListAttribute");
                    } else if (rawClass.isSet()) {
                        attributeType = AttributeType.SetAttribute.name();
                        imports.put(attributeType, "jakarta.persistence.metamodel.SetAttribute");
                    } else if (rawClass.isMap()) {
                        attributeType = AttributeType.MapAttribute.name();
                        imports.put(attributeType, "jakarta.persistence.metamodel.MapAttribute");
                    } else if (rawClass.isCollection()) {
                        attributeType = AttributeType.CollectionAttribute.name();
                        imports.put(attributeType, "jakarta.persistence.metamodel.CollectionAttribute");
                    } else {
                        attributeType = AttributeType.SingularAttribute.name();
                        imports.put(attributeType, "jakarta.persistence.metamodel.SingularAttribute");
                    }
                    if (mappingAccessor.isMapAccessor()) {
                        if (mappingAccessor.isMappedKeyMapAccessor()) {
                            MetadataClass mapKeyClass = ((MappedKeyMapAccessor) mappingAccessor).getMapKeyClass();
                            types = types + ", " + getUnqualifiedType(mapKeyClass.getName(), imports) + ", " + getUnqualifiedType(mappingAccessor.getReferenceClassName(), imports);
                        } else {
                            String mapKeyType;
                            if (annotatedElement.isGenericCollectionType()) {
                                // Grab the map key class from the generic.
                                mapKeyType = annotatedElement.getGenericType().get(1);
                            } else {
                                if (mappingAccessor.getReferenceDescriptor().hasIdAccessor()) {
                                    // Grab the id type from the reference descriptor, now there's a handle!
                                    MappingAccessor idAccessor = mappingAccessor.getReferenceDescriptor().getIdAccessors().values().iterator().next();
                                    mapKeyType = idAccessor.getReferenceClassName();
                                } else {
                                    // We don't know at this point so just use the catch all default.
                                    mapKeyType = TypeVisitor.GENERIC_TYPE;
                                }
                            }
                            types = types + ", " + getUnqualifiedType(mapKeyType, imports) + ", " + getUnqualifiedType(mappingAccessor.getReferenceClassName(), imports);
                        }
                    } else {
                        types = types + ", " + getUnqualifiedType(mappingAccessor.getReferenceClassName(), imports);
                    }
                }
                // Add the mapping attribute to the list of attributes for this class.
                attributes.add("    public static volatile " + attributeType + "<" + types + "> " + annotatedElement.getAttributeName() + ";\n");
            }
        }
        // Will import the parent as well if needed.
        String parent = writeImportStatements(imports, accessor, writer, persistenceUnit, canonicalpackage);
        if (generateGenerated) {
            // Write out the generation annotations.
            String elVersion = "EclipseLink-" + Version.getVersion() + ".v" + Version.getBuildDate() + "-r" + Version.getBuildRevision();
            writer.append("@Generated(value=\"");
            if (isNewJava) {
                writer.append(CanonicalModelProcessor.class.getName());
            } else {
                writer.append(elVersion);
            }
            writer.append("\"");
            if (generateTimestamp) {
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                writer.append(", date=\"" + sdf.format(date) + "\"");
            }
            if (isNewJava && generateComments) {
                writer.append(", comments=\"");
                writer.append(elVersion);
                writer.append("\"");
            }
            writer.append(")\n");
        }
        writer.append("@StaticMetamodel(" + className + ".class)\n");
        int modifier = accessor.getAccessibleObject().getModifiers();
        writer.append(java.lang.reflect.Modifier.toString(modifier) + " class " + canonicalName);
        if (parent == null) {
            writer.append(" { \n\n");
        } else {
            writer.append(" extends " + parent + " {\n\n");
        }
        // Go through the attributes and write them out.
        for (String str : attributes) {
            writer.append(str);
        }
        writer.append("\n}");
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
            writer = null;
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MappedKeyMapAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappedKeyMapAccessor) Date(java.util.Date) JavaFileObject(javax.tools.JavaFileObject) MetadataAnnotatedElement(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotatedElement) MetadataClass(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass) ClassAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor) MappingAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor) SimpleDateFormat(java.text.SimpleDateFormat) Writer(java.io.Writer)

Example 3 with ClassAccessor

use of org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor in project eclipselink by eclipse-ee4j.

the class ConvertMetadata method verify.

/**
 * INTERNAL:
 * Verify mapping passed to register {@code AttributeConverter} class.
 * @param mapping        Database attribute mapping.
 * @param referenceClass JPA annotated class.
 * @param accessor       Class accessor.
 * @param embeddedAttributeName Content of {@code <name>}
 *        from {@code attributeName="value.<name>"}. This value shall never
 *        be {@code null} when {@code @ElementCollection} mapping is being
 *        processed.
 */
private MetadataClass verify(final DatabaseMapping mapping, final MetadataClass referenceClass, final ClassAccessor accessor, final String embeddedAttributeName) throws ValidationException {
    // Validate the attribute name first if there is one.
    if (hasAttributeName()) {
        String attributeName;
        // Aggregate object mapping
        if (mapping.isAggregateObjectMapping()) {
            attributeName = getAttributeName();
        // Coming from @ElementCollection mapping with value.<name> attributeName.
        } else if (mapping.isAggregateCollectionMapping() && embeddedAttributeName != null && embeddedAttributeName.length() > 0) {
            attributeName = embeddedAttributeName;
        // Unsupported mapping, throw an exception
        } else {
            throw ValidationException.invalidMappingForConvertWithAttributeName(accessor.getJavaClassName(), mapping.getAttributeName());
        }
        // Validate the attribute name existing on the embeddable and update
        // the reference class.
        final ClassAccessor embeddableAccessor = getProject().getEmbeddableAccessor(referenceClass);
        final MappingAccessor mappingAccessor = embeddableAccessor.getDescriptor().getMappingAccessor(attributeName);
        if (mappingAccessor == null) {
            throw ValidationException.embeddableAttributeNameForConvertNotFound(accessor.getJavaClassName(), mapping.getAttributeName(), embeddableAccessor.getJavaClassName(), getAttributeName());
        }
        return mappingAccessor.getReferenceClass();
    } else {
        // In an aggregate object case, the attribute name must be specified.
        if (mapping.isAggregateObjectMapping()) {
            throw ValidationException.missingMappingConvertAttributeName(accessor.getJavaClassName(), mapping.getAttributeName());
        }
    }
    return referenceClass;
}
Also used : ClassAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor) MappingAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor)

Example 4 with ClassAccessor

use of org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor in project eclipselink by eclipse-ee4j.

the class MappingAccessor method hashCode.

@Override
public int hashCode() {
    int result = super.hashCode();
    ClassAccessor classAccessor = getClassAccessor();
    String attributeType = getAttributeType();
    result = 31 * result + (classAccessor != null ? classAccessor.hashCode() : 0);
    result = 31 * result + (attributeType != null ? attributeType.hashCode() : 0);
    result = 31 * result + (m_field != null ? m_field.hashCode() : 0);
    return result;
}
Also used : ClassAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor)

Example 5 with ClassAccessor

use of org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor in project eclipselink by eclipse-ee4j.

the class ObjectAccessor method getSimplePKType.

/**
 * INTERNAL:
 * Used to process primary keys and DerivedIds.
 */
protected MetadataClass getSimplePKType() {
    MetadataDescriptor referenceDescriptor = getReferenceDescriptor();
    ClassAccessor referenceAccessor = referenceDescriptor.getClassAccessor();
    if (referenceAccessor.hasDerivedId()) {
        // Recurse through to get the simple type.
        return ((ObjectAccessor) referenceDescriptor.getMappingAccessor(referenceDescriptor.getIdAttributeName())).getSimplePKType();
    } else {
        // Validate on their basic mapping.
        return referenceDescriptor.getMappingAccessor(referenceDescriptor.getIdAttributeName()).getRawClass();
    }
}
Also used : ClassAccessor(org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor) MetadataDescriptor(org.eclipse.persistence.internal.jpa.metadata.MetadataDescriptor)

Aggregations

ClassAccessor (org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor)10 HashMap (java.util.HashMap)3 MappingAccessor (org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor)3 ArrayList (java.util.ArrayList)2 DynamicClassLoader (org.eclipse.persistence.dynamic.DynamicClassLoader)2 MetadataDescriptor (org.eclipse.persistence.internal.jpa.metadata.MetadataDescriptor)2 EntityAccessor (org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor)2 MetadataClass (org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass)2 Writer (java.io.Writer)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 Hashtable (java.util.Hashtable)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 JavaFileObject (javax.tools.JavaFileObject)1 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)1 DynamicType (org.eclipse.persistence.dynamic.DynamicType)1 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)1