Search in sources :

Example 6 with InstanceVariableAttributeAccessor

use of org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor in project eclipselink by eclipse-ee4j.

the class XMLVariableXPathObjectMapping method initialize.

@Override
public void initialize(AbstractSession session) throws DescriptorException {
    // modified so that reference class on composite mappings is no longer mandatory
    String referenceClassName = getReferenceClassName();
    if ((this.referenceClass == null) && (referenceClassName != null)) {
        if (!referenceClassName.equals(XMLConstants.UNKNOWN_OR_TRANSIENT_CLASS)) {
            setReferenceClass(session.getDatasourcePlatform().getConversionManager().convertClassNameToClass(referenceClassName));
        }
    }
    if (this.referenceClass != null) {
        super.initialize(session);
    } else {
        // below should be the same as AbstractCompositeObjectMapping.initialize
        if (this.field == null) {
            throw DescriptorException.fieldNameNotSetInMapping(this);
        }
        setField(getDescriptor().buildField(this.field));
        setFields(collectFields());
        // initialize the converter - if necessary
        if (hasConverter()) {
            getConverter().initialize(this, session);
        }
    }
    final XMLInverseReferenceMapping inverseReferenceMapping = getInverseReferenceMapping();
    if (null != inverseReferenceMapping && null != inverseReferenceMapping.getAttributeAccessor()) {
        inverseReferenceMapping.getAttributeAccessor().initializeAttributes(this.referenceClass);
    }
    if (variableAttributeName != null) {
        this.variableAttributeAccessor = new InstanceVariableAttributeAccessor();
        this.variableAttributeAccessor.setAttributeName(variableAttributeName);
        this.variableAttributeAccessor.initializeAttributes(this.getReferenceClass());
    } else if (variableGetMethodName != null) {
        this.variableAttributeAccessor = new MethodAttributeAccessor();
        this.variableAttributeAccessor.setAttributeName("VARIABLE");
        ((MethodAttributeAccessor) this.variableAttributeAccessor).setGetMethodName(variableGetMethodName);
        if (variableSetMethodName == null) {
            this.variableAttributeAccessor.setIsWriteOnly(true);
        } else {
            ((MethodAttributeAccessor) this.variableAttributeAccessor).setSetMethodName(variableSetMethodName);
        }
        this.variableAttributeAccessor.initializeAttributes(this.getReferenceClass());
    }
}
Also used : InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor)

Example 7 with InstanceVariableAttributeAccessor

use of org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor in project eclipselink by eclipse-ee4j.

the class SimpleSerializeFetchGroupTests method attrAndVHContainSameObjectAfterGetRealAttributeValue.

@Test
public void attrAndVHContainSameObjectAfterGetRealAttributeValue() throws Exception {
    String errorMsg = "";
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        Query query = em.createQuery("SELECT e FROM Employee e WHERE e.address IS NOT NULL and e.manager IS NOT NULL");
        List<Employee> employees = query.getResultList();
        OneToOneMapping addressMapping = (OneToOneMapping) employeeDescriptor.getMappingForAttributeName("address");
        OneToOneMapping managerMapping = (OneToOneMapping) employeeDescriptor.getMappingForAttributeName("manager");
        InstanceVariableAttributeAccessor addressAccessor = new InstanceVariableAttributeAccessor();
        addressAccessor.setAttributeName("m_address");
        addressAccessor.initializeAttributes(Employee.class);
        InstanceVariableAttributeAccessor managerAccessor = new InstanceVariableAttributeAccessor();
        managerAccessor.setAttributeName("manager");
        managerAccessor.initializeAttributes(Employee.class);
        AbstractSession session = (AbstractSession) ((EntityManagerImpl) em.getDelegate()).getActiveSession();
        for (Employee emp : employees) {
            String localErrorMsg = "";
            Address addressVH = (Address) addressMapping.getRealAttributeValueFromObject(emp, session);
            Address addressAttr = (Address) addressAccessor.getAttributeValueFromObject(emp);
            if (addressVH != addressAttr) {
                localErrorMsg += "\n\taddressVH = " + addressVH + " != addressAttr = " + addressAttr;
            }
            Employee managerVH = (Employee) managerMapping.getRealAttributeValueFromObject(emp, session);
            Employee managerAttr = (Employee) managerAccessor.getAttributeValueFromObject(emp);
            if (managerVH != managerAttr) {
                localErrorMsg += "\n\tmanagerVH = " + managerVH + " != managerAttr = " + managerAttr;
            }
            if (localErrorMsg.length() > 0) {
                localErrorMsg = emp.toString() + localErrorMsg + "\n";
                errorMsg += localErrorMsg;
            }
        }
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
    if (errorMsg.length() > 0) {
        errorMsg = '\n' + errorMsg;
        fail(errorMsg);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) TypedQuery(jakarta.persistence.TypedQuery) Query(jakarta.persistence.Query) Address(org.eclipse.persistence.testing.models.jpa.advanced.Address) InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) Test(org.junit.Test)

Example 8 with InstanceVariableAttributeAccessor

use of org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor in project eclipselink by eclipse-ee4j.

the class ForeignReferenceMapping method validateBeforeInitialization.

/**
 * INTERNAL:
 * To validate mappings declaration
 */
@Override
public void validateBeforeInitialization(AbstractSession session) throws DescriptorException {
    super.validateBeforeInitialization(session);
    // then the mapping must be reverted to no use indirection.
    if ((this.indirectionPolicy instanceof WeavedObjectBasicIndirectionPolicy) && !ClassConstants.PersistenceWeavedLazy_Class.isAssignableFrom(getDescriptor().getJavaClass())) {
        Object[] args = new Object[2];
        args[0] = getAttributeName();
        args[1] = getDescriptor().getJavaClass();
        session.log(SessionLog.WARNING, SessionLog.METADATA, "metadata_warning_ignore_lazy", args);
        setIndirectionPolicy(new NoIndirectionPolicy());
    }
    if (getAttributeAccessor() instanceof InstanceVariableAttributeAccessor) {
        Class<?> attributeType = ((InstanceVariableAttributeAccessor) getAttributeAccessor()).getAttributeType();
        this.indirectionPolicy.validateDeclaredAttributeType(attributeType, session.getIntegrityChecker());
    } else if (getAttributeAccessor().isMethodAttributeAccessor()) {
        // 323148
        Class<?> returnType = ((MethodAttributeAccessor) getAttributeAccessor()).getGetMethodReturnType();
        this.indirectionPolicy.validateGetMethodReturnType(returnType, session.getIntegrityChecker());
        Class<?> parameterType = ((MethodAttributeAccessor) getAttributeAccessor()).getSetMethodParameterType();
        this.indirectionPolicy.validateSetMethodParameterType(parameterType, session.getIntegrityChecker());
    }
}
Also used : WeavedObjectBasicIndirectionPolicy(org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy) InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) NoIndirectionPolicy(org.eclipse.persistence.internal.indirection.NoIndirectionPolicy)

Example 9 with InstanceVariableAttributeAccessor

use of org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor in project eclipselink by eclipse-ee4j.

the class DatabaseMapping method setGetMethodName.

/**
 * PUBLIC:
 * This method is invoked reflectively on the reference object to return the value of the
 * attribute in the object. This method sets the name of the getMethodName.
 */
public void setGetMethodName(String methodName) {
    if (methodName == null) {
        return;
    }
    // This is done because setting attribute name by defaults create InstanceVariableAttributeAccessor
    if (getAttributeAccessor() instanceof InstanceVariableAttributeAccessor) {
        String attributeName = this.attributeAccessor.getAttributeName();
        setAttributeAccessor(new MethodAttributeAccessor());
        getAttributeAccessor().setAttributeName(attributeName);
    }
    ((MethodAttributeAccessor) getAttributeAccessor()).setGetMethodName(methodName);
}
Also used : InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor)

Example 10 with InstanceVariableAttributeAccessor

use of org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor in project eclipselink by eclipse-ee4j.

the class ManagedTypeImpl method initialize.

/**
 * INTERNAL:
 * Initialize the members of this ManagedType based on the mappings defined on the descriptor.
 * We process the appropriate Map, List, Set, Collection or Object/primitive types.<p>
 * Initialization should occur after all types in the metamodel have been created already.
 */
protected void initialize() {
    // See MappedSuperclassType.getMemberFromInheritingType()
    if (null != this.members) {
        // this is already initialized
        return;
    }
    this.members = new HashMap<String, Attribute<X, ?>>();
    // Get and process all mappings on the relationalDescriptor
    for (DatabaseMapping mapping : getDescriptor().getMappings()) {
        AttributeImpl<X, ?> member = null;
        // Tie into the collection hierarchy at a lower level
        if (mapping instanceof CollectionMapping) {
            // Handle 1:m, n:m collection mappings
            CollectionMapping colMapping = (CollectionMapping) mapping;
            ContainerPolicy collectionContainerPolicy = colMapping.getContainerPolicy();
            if (collectionContainerPolicy.isMapPolicy()) {
                // Handle the 3 Map type mappings (policy.isMappedKeyMapPolicy()) is handled by isMapPolicy())
                member = new MapAttributeImpl(this, colMapping, true);
            // check mapping.attributeAcessor.attributeField.type=Collection
            } else if (collectionContainerPolicy.isListPolicy()) {
                // This seems very over complex...
                /**
                 * Handle lazy Collections and Lists and the fact that both return an IndirectList policy.
                 * We check the type on the attributeField of the attributeAccessor on the mapping
                 */
                Class<?> aType = null;
                // 325699: AttributeAccessor is subclassed by both IntanceVariableAttributeAccessor (JPA) and ValuesAccessor (Dynamic JPA)
                if (colMapping.getAttributeAccessor() instanceof ValuesAccessor) {
                    member = new ListAttributeImpl(this, colMapping);
                } else if (colMapping.getAttributeAccessor() instanceof InstanceVariableAttributeAccessor) {
                    Field aField = ((InstanceVariableAttributeAccessor) colMapping.getAttributeAccessor()).getAttributeField();
                    // MappedSuperclasses need special handling to get their type from an inheriting subclass
                    if (null == aField) {
                        // MappedSuperclass field will not be set
                        if (this.isMappedSuperclass()) {
                            // get inheriting subtype member (without handling @override annotations)
                            MappedSuperclassTypeImpl aMappedSuperclass = ((MappedSuperclassTypeImpl) this);
                            AttributeImpl inheritingTypeMember = aMappedSuperclass.getMemberFromInheritingType(colMapping.getAttributeName());
                            // 322166: If attribute is defined on this current ManagedType (and not on a superclass) - do not attempt a reflective call on a superclass
                            if (null != inheritingTypeMember) {
                                // Verify we have an attributeAccessor
                                aField = ((InstanceVariableAttributeAccessor) inheritingTypeMember.getMapping().getAttributeAccessor()).getAttributeField();
                            }
                        }
                    }
                    // 322166: The attribute may be defined on the current ManagedType - not inherited
                    if (null == aField) {
                        // Check attributeName when the field is null
                        aType = this.getTypeClassFromAttributeOrMethodLevelAccessor(mapping);
                    } else {
                        aType = aField.getType();
                    }
                    // This attribute is declared as List
                    if ((aType != null) && List.class.isAssignableFrom(aType)) {
                        member = new ListAttributeImpl(this, colMapping, true);
                    } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                        // This attribute is therefore declared as Collection
                        member = new CollectionAttributeImpl(this, colMapping, true);
                    } else {
                        member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                    }
                } else {
                    // handle variations of missing get/set methods - only for Collection vs List
                    if (colMapping.getAttributeAccessor() instanceof MethodAttributeAccessor) {
                        /**
                         * The following call will perform a getMethod call for us.
                         * If no getMethod exists, we will secondarily check the getMethodName below.
                         */
                        aType = colMapping.getAttributeAccessor().getAttributeClass();
                        if ((aType != null) && List.class.isAssignableFrom(aType)) {
                            member = new ListAttributeImpl(this, colMapping, true);
                        } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                            member = new CollectionAttributeImpl(this, colMapping, true);
                        } else {
                            /**
                             * In this block we have the following scenario:
                             * 1) The access type is "field"
                             * 2) The get method is not set on the entity
                             * 3) The get method is named differently than the attribute
                             */
                            // Type may be null when no getMethod exists for the class for a ManyToMany mapping
                            // Here we check the returnType on the declared method on the class directly
                            String getMethodName = ((MethodAttributeAccessor) colMapping.getAttributeAccessor()).getGetMethodName();
                            if (null == getMethodName) {
                                // Check declaredFields in the case where we have no getMethod or getMethodName
                                try {
                                    Field field = null;
                                    if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                        try {
                                            field = AccessController.doPrivileged(new PrivilegedGetDeclaredField(this.getJavaType(), colMapping.getAttributeName(), false));
                                        } catch (PrivilegedActionException exception) {
                                            member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                        }
                                    } else {
                                        field = PrivilegedAccessHelper.getDeclaredField(this.getJavaType(), colMapping.getAttributeName(), false);
                                    }
                                    if (null == field) {
                                        member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                    } else {
                                        aType = field.getType();
                                        if ((aType != null) && List.class.isAssignableFrom(aType)) {
                                            member = new ListAttributeImpl(this, colMapping, true);
                                        } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                                            member = new CollectionAttributeImpl(this, colMapping, true);
                                        } else {
                                            member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                        }
                                    }
                                } catch (Exception e) {
                                    member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                }
                            } else {
                                /**
                                 * Field access Handling:
                                 * If a get method name exists, we check the return type on the method directly
                                 * using reflection.
                                 * In all failure cases we default to the List type.
                                 */
                                try {
                                    Method aMethod = null;
                                    if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                        aMethod = AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(this.getJavaType(), getMethodName, null));
                                    } else {
                                        aMethod = PrivilegedAccessHelper.getDeclaredMethod(this.getJavaType(), getMethodName, null);
                                    }
                                    if (null == aMethod) {
                                        member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                    } else {
                                        aType = aMethod.getReturnType();
                                        if ((aType != null) && List.class.isAssignableFrom(aType)) {
                                            member = new ListAttributeImpl(this, colMapping, true);
                                        } else if ((aType != null) && Collection.class.isAssignableFrom(aType)) {
                                            member = new CollectionAttributeImpl(this, colMapping, true);
                                        } else {
                                            member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                        }
                                    }
                                } catch (Exception e) {
                                    member = initializePluralAttributeTypeNotFound(this, colMapping, true);
                                }
                            }
                        }
                    }
                }
            } else {
                // Handle non-lazy Collection or Set type mappings (IndirectSet.isAssignableFrom(Set.class) == false)
                if ((collectionContainerPolicy.getContainerClass() != null) && Set.class.isAssignableFrom(collectionContainerPolicy.getContainerClass())) {
                    member = new SetAttributeImpl(this, colMapping, true);
                } else {
                    // Check for non-lazy Collection policy possibly instantiated to a Set or List (both of which is ignored)
                    if (collectionContainerPolicy.isCollectionPolicy()) {
                        member = new CollectionAttributeImpl(this, colMapping, true);
                    } else {
                        // Handle Collection type mappings as a default (we should never get here)
                        // TODO: System.out.println("_Warning: defaulting to non-Set specific Collection type on " + colMapping);
                        member = new CollectionAttributeImpl(this, colMapping);
                    }
                }
            }
        } else {
            // Handle 1:1 single object and direct mappings including EnumSet
            member = new SingularAttributeImpl(this, mapping, true);
        }
        // 303063: secondary check for a null value put - should never happen but this will show on code coverage
        if (null == member) {
            AbstractSessionLog.getLog().log(SessionLog.FINEST, "metamodel_attribute_getmember_is_null", mapping.getAttributeName(), this, descriptor);
        }
        this.members.put(mapping.getAttributeName(), member);
    }
}
Also used : CollectionAttribute(jakarta.persistence.metamodel.CollectionAttribute) PluralAttribute(jakarta.persistence.metamodel.PluralAttribute) Attribute(jakarta.persistence.metamodel.Attribute) MapAttribute(jakarta.persistence.metamodel.MapAttribute) SingularAttribute(jakarta.persistence.metamodel.SingularAttribute) SetAttribute(jakarta.persistence.metamodel.SetAttribute) ListAttribute(jakarta.persistence.metamodel.ListAttribute) InstanceVariableAttributeAccessor(org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) Field(java.lang.reflect.Field) PrivilegedGetDeclaredField(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) List(java.util.List) PrivilegedActionException(java.security.PrivilegedActionException) ValuesAccessor(org.eclipse.persistence.internal.dynamic.ValuesAccessor) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) PrivilegedGetDeclaredMethod(org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod) Method(java.lang.reflect.Method) PrivilegedActionException(java.security.PrivilegedActionException) ContainerPolicy(org.eclipse.persistence.internal.queries.ContainerPolicy) Collection(java.util.Collection) MethodAttributeAccessor(org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor) CollectionMapping(org.eclipse.persistence.mappings.CollectionMapping)

Aggregations

InstanceVariableAttributeAccessor (org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor)11 MethodAttributeAccessor (org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor)8 Method (java.lang.reflect.Method)4 Field (java.lang.reflect.Field)3 PrivilegedActionException (java.security.PrivilegedActionException)3 PrivilegedGetDeclaredField (org.eclipse.persistence.internal.security.PrivilegedGetDeclaredField)3 PrivilegedGetDeclaredMethod (org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod)3 EntityManager (jakarta.persistence.EntityManager)2 Query (jakarta.persistence.Query)2 TypedQuery (jakarta.persistence.TypedQuery)2 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)2 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)2 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)2 AttributeAccessor (org.eclipse.persistence.mappings.AttributeAccessor)2 OneToOneMapping (org.eclipse.persistence.mappings.OneToOneMapping)2 Test (org.junit.Test)2 Attribute (jakarta.persistence.metamodel.Attribute)1 CollectionAttribute (jakarta.persistence.metamodel.CollectionAttribute)1 ListAttribute (jakarta.persistence.metamodel.ListAttribute)1 MapAttribute (jakarta.persistence.metamodel.MapAttribute)1