Search in sources :

Example 6 with CMPPolicy

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

the class ProjectClassGeneratorWithCMPDescriptorTest method setup.

@Override
protected void setup() {
    project = new org.eclipse.persistence.testing.models.employee.relational.EmployeeProject();
    // initialize new CMP descriptor with non-default settings
    CMPPolicy cmpPolicy = new CMPPolicy();
    cmpPolicy.setPessimisticLockingPolicy(new PessimisticLockingPolicy());
    cmpPolicy.setDeferModificationsUntilCommit(5);
    cmpPolicy.setForceUpdate(true);
    cmpPolicy.setNonDeferredCreateTime(1000);
    cmpPolicy.setUpdateAllFields(true);
    cmpPolicy.setPessimisticLockingPolicy(new PessimisticLockingPolicy());
    cmpPolicy.getPessimisticLockingPolicy().setLockingMode(ObjectLevelReadQuery.LOCK_NOWAIT);
    // set CMP descriptor to Address descriptor
    project.getDescriptor(org.eclipse.persistence.testing.models.employee.domain.Address.class).setCMPPolicy(cmpPolicy);
}
Also used : CMPPolicy(org.eclipse.persistence.descriptors.CMPPolicy) PessimisticLockingPolicy(org.eclipse.persistence.descriptors.PessimisticLockingPolicy)

Example 7 with CMPPolicy

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

the class ProjectClassGeneratorWithCMPDescriptorTest method verify.

@Override
protected void verify() {
    CMPPolicy cmpPolicy = project.getDescriptor(org.eclipse.persistence.testing.models.employee.domain.Address.class).getCMPPolicy();
    CMPPolicy generatedCMPPolicy = generatedProject.getDescriptor(org.eclipse.persistence.testing.models.employee.domain.Address.class).getCMPPolicy();
    String errors = new String();
    if (generatedCMPPolicy == null) {
        errors += "CMPPolicy is null.\n";
    } else {
        if (generatedCMPPolicy.getDeferModificationsUntilCommit() != cmpPolicy.getDeferModificationsUntilCommit()) {
            errors += "CMPPolicy: deferModificationsUntilCommit setting is not the same.\n";
        }
        if (generatedCMPPolicy.getForceUpdate() != cmpPolicy.getForceUpdate()) {
            errors += "CMPPolicy: forceUpdate setting is not the same.\n";
        }
        if (generatedCMPPolicy.getNonDeferredCreateTime() != cmpPolicy.getNonDeferredCreateTime()) {
            errors += "CMPPolicy: nonDeferredCreateTime setting is not the same.\n";
        }
        if (generatedCMPPolicy.getUpdateAllFields() != cmpPolicy.getUpdateAllFields()) {
            errors += "CMPPolicy: updateAllFields setting is not the same.\n";
        }
        if (generatedCMPPolicy.getPessimisticLockingPolicy() == null) {
            errors += "CMPPolicy: pessimistic locking policy is null\n";
        } else if (generatedCMPPolicy.getPessimisticLockingPolicy().getLockingMode() != cmpPolicy.getPessimisticLockingPolicy().getLockingMode()) {
            errors += "PessimisticLockingPolicy: locking mode is not the same\n";
        }
    }
    if (errors.length() > 0) {
        throw new TestErrorException("The following settings of the generated project instance does not have the expected value:\n" + errors);
    }
}
Also used : CMPPolicy(org.eclipse.persistence.descriptors.CMPPolicy) TestErrorException(org.eclipse.persistence.testing.framework.TestErrorException)

Example 8 with CMPPolicy

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

the class EntityManagerImpl method findInternal.

/**
 * Find by primary key.
 *
 * @param descriptor
 *            - the entity class to find.
 * @param id
 *            - the entity primary key value, or primary key class, or a
 *            List of primary key values.
 * @return the found entity instance or null, if the entity does not exist.
 * @throws IllegalArgumentException
 *             if the first argument does not denote an entity type or the
 *             second argument is not a valid type for that entity's primary
 *             key.
 */
protected Object findInternal(ClassDescriptor descriptor, AbstractSession session, Object id, LockModeType lockMode, Map<String, Object> properties) {
    if (id == null) {
        // gf721 - check for null PK
        throw new IllegalArgumentException(ExceptionLocalization.buildMessage("null_pk"));
    }
    Object primaryKey;
    if (id instanceof List) {
        if (descriptor.getCacheKeyType() == CacheKeyType.ID_VALUE) {
            if (((List) id).isEmpty()) {
                primaryKey = null;
            } else {
                primaryKey = ((List) id).get(0);
            }
        } else {
            primaryKey = new CacheId(((List) id).toArray());
        }
    } else if (id instanceof CacheId) {
        primaryKey = id;
    } else {
        CMPPolicy policy = descriptor.getCMPPolicy();
        Class<Object> pkClass = policy.getPKClass();
        if ((pkClass != null) && (pkClass != id.getClass()) && (!BasicTypeHelperImpl.getInstance().isStrictlyAssignableFrom(pkClass, id.getClass()))) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("invalid_pk_class", new Object[] { descriptor.getCMPPolicy().getPKClass(), id.getClass() }));
        }
        primaryKey = policy.createPrimaryKeyFromId(id, session);
    }
    // Must avoid using the new JPA 2.0 Enum values directly to allow JPA 1.0 jars to still work.
    if (lockMode != null && (lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_READ) || lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_WRITE) || lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_FORCE_INCREMENT))) {
        // PERF: check if the UnitOfWork has pessimistically locked objects to avoid a cache query
        if (session.isUnitOfWork() && ((UnitOfWorkImpl) session).hasPessimisticLockedObjects()) {
            ReadObjectQuery query = new ReadObjectQuery();
            query.setReferenceClass(descriptor.getJavaClass());
            query.setSelectionId(primaryKey);
            query.checkCacheOnly();
            Object cachedEntity = session.executeQuery(query);
            if (cachedEntity != null && ((UnitOfWorkImpl) session).isPessimisticLocked(cachedEntity)) {
                return cachedEntity;
            }
        }
    }
    // Get the read object query and apply the properties to it.
    // PERF: use descriptor defined query to avoid extra query creation.
    ReadObjectQuery query = descriptor.getQueryManager().getReadObjectQuery();
    if (query == null) {
        // The properties/query hints and setIsExecutionClone etc. is set
        // in the getReadObjectQuery.
        query = getReadObjectQuery(descriptor.getJavaClass(), primaryKey, properties);
    } else {
        query.checkPrepare(session, null);
        query = (ReadObjectQuery) query.clone();
        // Apply the properties if there are some.
        QueryHintsHandler.apply(properties, query, session.getLoader(), session);
        query.setIsExecutionClone(true);
        query.setSelectionId(primaryKey);
    }
    // the properties.
    if (properties == null || (!properties.containsKey(QueryHints.CACHE_USAGE) && !properties.containsKey(QueryHints.CACHE_RETRIEVE_MODE) && !properties.containsKey(QueryHints.CACHE_STORE_MODE) && !properties.containsKey("jakarta.persistence.cacheRetrieveMode") && !properties.containsKey("jakarta.persistence.cacheStoreMode"))) {
        query.conformResultsInUnitOfWork();
    }
    return executeQuery(query, lockMode, session);
}
Also used : CMPPolicy(org.eclipse.persistence.descriptors.CMPPolicy) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) CacheId(org.eclipse.persistence.internal.identitymaps.CacheId) List(java.util.List) ArrayList(java.util.ArrayList)

Example 9 with CMPPolicy

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

the class CMP3Policy method initializePrimaryKeyFields.

/**
 * INTERNAL:
 * Cache the bean's primary key fields so speed up creating of primary key
 * objects and initialization of beans.
 *
 * Note, we have to re-look up the fields for the bean class since
 * these fields may have been loaded with the wrong loader (thank you Kirk).
 * If the key is compound, we also have to look up the fields for the key.
 */
protected KeyElementAccessor[] initializePrimaryKeyFields(Class<?> keyClass, AbstractSession session) {
    KeyElementAccessor[] pkAttributes = null;
    ClassDescriptor aDescriptor = this.getDescriptor();
    fieldToAccessorMap = new HashMap<DatabaseField, KeyElementAccessor>();
    int numberOfIDFields = aDescriptor.getPrimaryKeyFields().size();
    pkAttributes = new KeyElementAccessor[numberOfIDFields];
    Iterator<DatabaseField> attributesIter = aDescriptor.getPrimaryKeyFields().iterator();
    // Used fields in case it is an embedded class
    for (int i = 0; attributesIter.hasNext(); i++) {
        DatabaseField field = attributesIter.next();
        // We need to check all mappings for this field, not just the writable one and instead of
        // having multiple sections of duplicate code we'll just add the writable mapping directly
        // to the list.
        List allMappings = new ArrayList(1);
        addReadOnlyMappings(aDescriptor, field, allMappings);
        addWritableMapping(aDescriptor, field, allMappings);
        // This exception will be used to determine if the element (field or method) from
        // the mapping was found on the key class was found or not and throw an exception otherwise.
        Exception noSuchElementException = null;
        // Set the current key class ...
        Class<?> currentKeyClass = keyClass;
        // that mapping instead when we find it.
        for (int index = (allMappings.size() - 1); index >= 0; --index) {
            DatabaseMapping mapping = (DatabaseMapping) allMappings.get(index);
            // the id or not.
            if (aDescriptor.hasDerivedId() && !mapping.derivesId()) {
                // we initialize this portion of the composite id.
                if (mapping.isAggregateMapping() && allMappings.size() > 1) {
                    // Bail ... more mappings to check.
                    continue;
                }
            } else if (mapping.isForeignReferenceMapping() && !mapping.isOneToOneMapping()) {
                // JPA 2.0 allows DerrivedIds, so Id fields are either OneToOne or DirectToField mappings
                continue;
            }
            if (mapping.isAggregateMapping()) {
                // Either this aggregate is the key class, or we need to drill down further. Add the read
                // only and writable mappings from the aggregate.
                addReadOnlyMappings(mapping.getReferenceDescriptor(), field, allMappings);
                addWritableMapping(mapping.getReferenceDescriptor(), field, allMappings);
                // Since we added the mappings from this aggregate mapping, we should remove this aggregate
                // mapping from the allMappings list. Otherwise, if the mapping for the primary key field is
                // not found in the aggregate (or nested aggregate) then we will hit an infinite loop when
                // searching the aggregate and its mappings. Note: This is cautionary, since in reality, this
                // 'should' never happen, but if it does we certainly would rather throw an exception instead
                // of causing an infinite loop.
                allMappings.remove(mapping);
                // Update the index to parse the next mapping correctly.
                index = allMappings.size();
                // Update the key class now ...
                currentKeyClass = mapping.getReferenceDescriptor().getJavaClass();
            } else {
                String fieldName = (mapping.hasMapsIdValue()) ? mapping.getMapsIdValue() : mapping.getAttributeName();
                if (currentKeyClass == null || mapping.isMultitenantPrimaryKeyMapping()) {
                    // Without a currentKeyClass, the primary key is a non compound key but
                    // we may need to add any multitenant primary key mappings that are
                    // defined and we need an accessor for them. The same case will hold
                    // true when we do have a currentKeyClass. Multitenant primary keys
                    // must still be added.
                    pkAttributes[i] = new KeyIsElementAccessor(fieldName, field, mapping);
                    if (mapping.isAbstractDirectMapping()) {
                        setPKClass(ConversionManager.getObjectClass(mapping.getAttributeClassification()));
                    } else if (mapping.isOneToOneMapping()) {
                        ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                        // ensure the referenced descriptor was initialized
                        if (!session.isRemoteSession()) {
                            refDescriptor.initialize(session);
                        }
                        CMPPolicy refPolicy = refDescriptor.getCMPPolicy();
                        setPKClass(refPolicy.getPKClass());
                    }
                    fieldToAccessorMap.put(field, pkAttributes[i]);
                    noSuchElementException = null;
                } else {
                    if (mapping.isOneToOneMapping()) {
                        ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                        // ensure the referenced descriptor was initialized
                        if (!session.isRemoteSession()) {
                            refDescriptor.initialize(session);
                        }
                        CMPPolicy refPolicy = refDescriptor.getCMPPolicy();
                        if ((refPolicy != null) && refPolicy.isCMP3Policy() && (refPolicy.getPKClass() == currentKeyClass)) {
                            // Since the ref pk class is our pk class, get the accessor we need to pull the value out of the PK class for our field
                            OneToOneMapping refmapping = (OneToOneMapping) mapping;
                            DatabaseField targetKey = refmapping.getSourceToTargetKeyFields().get(field);
                            pkAttributes[i] = ((CMP3Policy) refPolicy).fieldToAccessorMap.get(targetKey);
                            // associate their accessor to our field so we can look it up when we need it
                            this.fieldToAccessorMap.put(field, pkAttributes[i]);
                            noSuchElementException = null;
                            break;
                        }
                    }
                    try {
                        pkAttributes[i] = new FieldAccessor(this, getField(currentKeyClass, fieldName), fieldName, field, mapping, currentKeyClass != keyClass);
                        fieldToAccessorMap.put(field, pkAttributes[i]);
                        noSuchElementException = null;
                    } catch (NoSuchFieldException ex) {
                        String getMethodName = null;
                        String setMethodName = null;
                        if (mapping.isObjectReferenceMapping() && ((ObjectReferenceMapping) mapping).getIndirectionPolicy().isWeavedObjectBasicIndirectionPolicy()) {
                            WeavedObjectBasicIndirectionPolicy weavedIndirectionPolicy = (WeavedObjectBasicIndirectionPolicy) ((ObjectReferenceMapping) mapping).getIndirectionPolicy();
                            if (weavedIndirectionPolicy.hasUsedMethodAccess()) {
                                getMethodName = weavedIndirectionPolicy.getGetMethodName();
                                setMethodName = weavedIndirectionPolicy.getSetMethodName();
                            }
                        } else {
                            getMethodName = mapping.getGetMethodName();
                            setMethodName = mapping.getSetMethodName();
                        }
                        if (getMethodName != null) {
                            // Must be a property.
                            try {
                                Method getMethod = null;
                                if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                    try {
                                        getMethod = AccessController.doPrivileged(new PrivilegedGetMethod(currentKeyClass, getMethodName, new Class<?>[] {}, true));
                                    } catch (PrivilegedActionException exception) {
                                        throw (NoSuchMethodException) exception.getException();
                                    }
                                } else {
                                    getMethod = PrivilegedAccessHelper.getMethod(currentKeyClass, getMethodName, new Class<?>[] {}, true);
                                }
                                Method setMethod = null;
                                if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                    try {
                                        setMethod = AccessController.doPrivileged(new PrivilegedGetMethod(currentKeyClass, setMethodName, new Class<?>[] { getMethod.getReturnType() }, true));
                                    } catch (PrivilegedActionException exception) {
                                        throw (NoSuchMethodException) exception.getException();
                                    }
                                } else {
                                    setMethod = PrivilegedAccessHelper.getMethod(currentKeyClass, setMethodName, new Class<?>[] { getMethod.getReturnType() }, true);
                                }
                                pkAttributes[i] = new PropertyAccessor(this, getMethod, setMethod, fieldName, field, mapping, currentKeyClass != keyClass);
                                this.fieldToAccessorMap.put(field, pkAttributes[i]);
                                noSuchElementException = null;
                            } catch (NoSuchMethodException exs) {
                                // not a field not a method, but a pk class is defined.  Check for other mappings
                                noSuchElementException = exs;
                            }
                        } else {
                            noSuchElementException = ex;
                        }
                        // accessor then we're dealing with a dynamic entity.
                        if (noSuchElementException != null && mapping.getAttributeAccessor().isValuesAccessor()) {
                            pkAttributes[i] = new ValuesFieldAccessor(fieldName, field, mapping, currentKeyClass != keyClass);
                            noSuchElementException = null;
                        }
                    }
                }
                if (mapping.derivesId() || noSuchElementException == null) {
                    // any more mappings
                    break;
                }
            }
        }
        if (noSuchElementException != null) {
            throw DescriptorException.errorUsingPrimaryKey(keyClass, getDescriptor(), noSuchElementException);
        }
    }
    return pkAttributes;
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) ArrayList(java.util.ArrayList) CMPPolicy(org.eclipse.persistence.descriptors.CMPPolicy) ArrayList(java.util.ArrayList) List(java.util.List) ObjectReferenceMapping(org.eclipse.persistence.mappings.ObjectReferenceMapping) PrivilegedActionException(java.security.PrivilegedActionException) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Method(java.lang.reflect.Method) PrivilegedGetMethod(org.eclipse.persistence.internal.security.PrivilegedGetMethod) DescriptorException(org.eclipse.persistence.exceptions.DescriptorException) PrivilegedActionException(java.security.PrivilegedActionException) WeavedObjectBasicIndirectionPolicy(org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy) PrivilegedGetMethod(org.eclipse.persistence.internal.security.PrivilegedGetMethod) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping)

Aggregations

CMPPolicy (org.eclipse.persistence.descriptors.CMPPolicy)9 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)4 PessimisticLockingPolicy (org.eclipse.persistence.descriptors.PessimisticLockingPolicy)3 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)3 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)3 OneToOneMapping (org.eclipse.persistence.mappings.OneToOneMapping)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 CacheId (org.eclipse.persistence.internal.identitymaps.CacheId)2 Method (java.lang.reflect.Method)1 PrivilegedActionException (java.security.PrivilegedActionException)1 DescriptorException (org.eclipse.persistence.exceptions.DescriptorException)1 WeavedObjectBasicIndirectionPolicy (org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy)1 PrivilegedGetMethod (org.eclipse.persistence.internal.security.PrivilegedGetMethod)1 ObjectReferenceMapping (org.eclipse.persistence.mappings.ObjectReferenceMapping)1 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)1 TestErrorException (org.eclipse.persistence.testing.framework.TestErrorException)1 EmployeeProject (org.eclipse.persistence.testing.models.employee.relational.EmployeeProject)1