Java源码示例:org.eclipse.persistence.descriptors.ClassDescriptor
示例1
@Override
public void process(MappingProcessorContext context) {
DatabaseMapping mapping = context.getMapping();
if (mapping instanceof AggregateObjectMapping) {
ClassDescriptor descriptor = mapping.getDescriptor();
Field referenceField =
FieldUtils.getFieldsListWithAnnotation(descriptor.getJavaClass(), EmbeddedParameters.class)
.stream().filter(f -> f.getName().equals(mapping.getAttributeName())).findFirst().orElse(null);
if (referenceField != null) {
EmbeddedParameters embeddedParameters =
referenceField.getAnnotation(EmbeddedParameters.class);
if (!embeddedParameters.nullAllowed())
((AggregateObjectMapping) mapping).setIsNullAllowed(false);
}
}
}
示例2
@Override
public void process(MappingProcessorContext context) {
DatabaseMapping mapping = context.getMapping();
ClassDescriptor descriptor = mapping.getDescriptor();
Field referenceField = FieldUtils.getAllFieldsList(descriptor.getJavaClass())
.stream().filter(f -> f.getName().equals(mapping.getAttributeName())).findFirst().orElse(null);
if (mapping.isOneToOneMapping()) {
OneToOneMapping oneToOneMapping = (OneToOneMapping) mapping;
if (SoftDelete.class.isAssignableFrom(oneToOneMapping.getReferenceClass())) {
if (mapping.isManyToOneMapping()) {
oneToOneMapping.setSoftDeletionForBatch(false);
oneToOneMapping.setSoftDeletionForValueHolder(false);
} else if (referenceField != null) {
OneToOne oneToOne = referenceField.getAnnotation(OneToOne.class);
if (oneToOne != null) {
if (Strings.isNullOrEmpty(oneToOne.mappedBy())) {
oneToOneMapping.setSoftDeletionForBatch(false);
oneToOneMapping.setSoftDeletionForValueHolder(false);
}
}
}
}
}
}
示例3
private Attribute getManagedAttribute(ClassDescriptor refDescriptor, DatabaseField dbField, LinkedList<Attribute> intrinsicAttribute) {
if (refDescriptor != null) {
for (DatabaseMapping refMapping : refDescriptor.getMappings()) {
if(!refMapping.getFields()
.stream()
.filter(field -> field == dbField)
.findAny()
.isPresent()){
continue;
}
if (refMapping.getFields().size() > 1) {
intrinsicAttribute.add((Attribute) refMapping.getProperty(Attribute.class));
if(refMapping.getReferenceDescriptor() == refDescriptor){ //self-relationship with composite pk
return (Attribute) refMapping.getProperty(Attribute.class);
} else {
return getManagedAttribute(refMapping.getReferenceDescriptor(), dbField, intrinsicAttribute);
}
} else if (!refMapping.getFields().isEmpty() && refMapping.getFields().get(0) == dbField) {
intrinsicAttribute.add((Attribute) refMapping.getProperty(Attribute.class));
return (Attribute) refMapping.getProperty(Attribute.class);
}
}
}
return null;
}
示例4
private DatabaseMapping getDatabaseMapping(ClassDescriptor descriptor, DatabaseField databaseField) {
DatabaseMapping databaseMapping = mappings.get(databaseField);
if (databaseMapping == null) {
for (DatabaseMapping m : descriptor.getMappings()) {
for (DatabaseField f : m.getFields()) {
if (mappings.get(f) == null) {
mappings.put(f, m);
}
if (databaseField == f) {
databaseMapping = m;
}
}
}
}
return databaseMapping;
}
示例5
/**
* Gets the inverse extension of the given {@link ClassDescriptor}.
*
* @param extensionEntityDescriptor the {@link ClassDescriptor} of which to get the inverse.
* @param entityType the type of the entity.
* @return the inverse extension of the given {@link ClassDescriptor}.
*/
protected OneToOneMapping findExtensionInverse(ClassDescriptor extensionEntityDescriptor, Class<?> entityType) {
Collection<DatabaseMapping> derivedIdMappings = extensionEntityDescriptor.getDerivesIdMappinps();
String extensionInfo = "(" + extensionEntityDescriptor.getJavaClass().getName() + " -> " + entityType.getName()
+ ")";
if (derivedIdMappings == null || derivedIdMappings.isEmpty()) {
throw new MetadataConfigurationException("Attempting to use extension framework, but extension "
+ extensionInfo + " does not have a valid inverse OneToOne Id mapping back to the extended data "
+ "object. Please ensure it is annotated property for use of the extension framework with JPA.");
} else if (derivedIdMappings.size() > 1) {
throw new MetadataConfigurationException("When attempting to determine the inverse relationship for use "
+ "with extension framework " + extensionInfo + " encountered more than one 'derived id' mapping, "
+ "there should be only one!");
}
DatabaseMapping inverseMapping = derivedIdMappings.iterator().next();
if (!(inverseMapping instanceof OneToOneMapping)) {
throw new MetadataConfigurationException("Identified an inverse derived id mapping for extension "
+ "relationship " + extensionInfo + " but it was not a one-to-one mapping: " + inverseMapping);
}
return (OneToOneMapping)inverseMapping;
}
示例6
/**
* Load Query Customizer based on annotations on fields and call customizer to modify descriptor.
*
* @param session the EclipseLink session.
*/
protected void loadQueryCustomizers(Session session) {
Map<Class, ClassDescriptor> descriptors = session.getDescriptors();
for (Class<?> entityClass : descriptors.keySet()) {
for (Field field : entityClass.getDeclaredFields()) {
String queryCustEntry = entityClass.getName() + "_" + field.getName();
buildQueryCustomizers(entityClass,field,queryCustEntry);
List<FilterGenerator> queryCustomizers = queryCustomizerMap.get(queryCustEntry);
if (queryCustomizers != null && !queryCustomizers.isEmpty()) {
Filter.customizeField(queryCustomizers, descriptors.get(entityClass), field.getName());
}
}
}
}
示例7
/**
* Checks class descriptors for {@link @DisableVersioning} annotations at the class level and removes the version
* database mapping for optimistic locking.
*
* @param session the current session.
*/
protected void handleDisableVersioning(Session session) {
Map<Class, ClassDescriptor> descriptors = session.getDescriptors();
if (descriptors == null || descriptors.isEmpty()) {
return;
}
for (ClassDescriptor classDescriptor : descriptors.values()) {
if (classDescriptor != null && AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
DisableVersioning.class) != null) {
OptimisticLockingPolicy olPolicy = classDescriptor.getOptimisticLockingPolicy();
if (olPolicy != null) {
classDescriptor.setOptimisticLockingPolicy(null);
}
}
}
}
示例8
/**
* Gets any {@link RemoveMapping}s out of the given {@link ClassDescriptor}.
*
* @param classDescriptor the {@link ClassDescriptor} to scan.
* @return a list of {@link RemoveMapping}s from the given {@link ClassDescriptor}.
*/
protected List<RemoveMapping> scanForRemoveMappings(ClassDescriptor classDescriptor) {
List<RemoveMapping> removeMappings = new ArrayList<RemoveMapping>();
RemoveMappings removeMappingsAnnotation = AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
RemoveMappings.class);
if (removeMappingsAnnotation == null) {
RemoveMapping removeMappingAnnotation = AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
RemoveMapping.class);
if (removeMappingAnnotation != null) {
removeMappings.add(removeMappingAnnotation);
}
} else {
for (RemoveMapping removeMapping : removeMappingsAnnotation.value()) {
removeMappings.add(removeMapping);
}
}
return removeMappings;
}
示例9
@Test
public void testConvertersEstabished_directAssignment() throws Exception {
ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("nonStandardDataType");
assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
assertNotNull("converter not assigned", converter);
assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
converter.getClass());
Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
f.setAccessible(true);
String attributeConverterClassName = (String) f.get(converter);
assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.testbo.NonStandardDataTypeConverter",
attributeConverterClassName);
}
示例10
@Test
public void testConvertersEstabished_autoApply() throws Exception {
ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("currencyProperty");
assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
assertNotNull("converter not assigned", converter);
assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
converter.getClass());
Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
f.setAccessible(true);
String attributeConverterClassName = (String) f.get(converter);
assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.converters.KualiDecimalConverter",
attributeConverterClassName);
}
示例11
@Test
public void testConvertersEstabished_autoApply_Boolean() throws Exception {
ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("booleanProperty");
assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
assertNotNull("converter not assigned", converter);
assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
converter.getClass());
Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
f.setAccessible(true);
String attributeConverterClassName = (String) f.get(converter);
assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter",
attributeConverterClassName);
}
示例12
@Override
public void customize(final Session session) throws SQLException {
for (ClassDescriptor descriptor : session.getDescriptors().values()) {
if (!descriptor.getTables().isEmpty()) {
// Take table name from @Table if exists
String tableName = null;
if (descriptor.getAlias().equalsIgnoreCase(descriptor.getTableName())) {
tableName = unqualify(descriptor.getJavaClassName());
} else {
tableName = descriptor.getTableName();
}
tableName = camelCaseToUnderscore(tableName);
descriptor.setTableName(tableName);
for (IndexDefinition index : descriptor.getTables().get(0).getIndexes()) {
index.setTargetTable(tableName);
}
Vector<DatabaseMapping> mappings = descriptor.getMappings();
camelCaseToUnderscore(mappings);
} else if (descriptor.isAggregateDescriptor() || descriptor.isChildDescriptor()) {
camelCaseToUnderscore(descriptor.getMappings());
}
}
}
示例13
@Override
public void customize(final Session session) throws Exception {
if (JPAThreadContext.infos.containsKey("properties")) {
final String prefix = ((Properties) JPAThreadContext.infos.get("properties")).getProperty("openejb.jpa.table_prefix");
final List<DatabaseTable> tables = new ArrayList<DatabaseTable>();
for (final ClassDescriptor cd : session.getDescriptors().values()) {
for (final DatabaseTable table : cd.getTables()) {
update(prefix, tables, table);
}
for (final DatabaseMapping mapping : cd.getMappings()) {
if (mapping instanceof ManyToManyMapping) {
update(prefix, tables, ((ManyToManyMapping) mapping).getRelationTable());
} else if (mapping instanceof DirectCollectionMapping) {
update(prefix, tables, ((DirectCollectionMapping) mapping).getReferenceTable());
} // TODO: else check we need to update something
}
}
final Sequence sequence = session.getDatasourcePlatform().getDefaultSequence();
if (sequence instanceof TableSequence) {
final TableSequence ts = ((TableSequence) sequence);
ts.setName(prefix + ts.getName());
}
}
}
示例14
@Override
public void preLogin(SessionEvent event) {
Session session = event.getSession();
Map<Class, ClassDescriptor> descriptorMap = session.getDescriptors();
for (Map.Entry<Class, ClassDescriptor> entry : descriptorMap.entrySet()) {
ClassDescriptor desc = entry.getValue();
if (SoftDelete.class.isAssignableFrom(desc.getJavaClass())) {
desc.getQueryManager().setAdditionalCriteria("this.deleteTs is null");
desc.setDeletePredicate(entity -> entity instanceof SoftDelete &&
PersistenceHelper.isLoaded(entity, "deleteTs") &&
((SoftDelete) entity).isDeleted());
}
List<DatabaseMapping> mappings = desc.getMappings();
Class entityClass = entry.getKey();
for (DatabaseMapping mapping : mappings) {
if (UUID.class.equals(getFieldType(entityClass, mapping.getAttributeName()))) {
((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
setDatabaseFieldParameters(session, mapping.getField());
}
}
}
}
示例15
@Override
protected Expression processOneToOneMapping(OneToOneMapping mapping) {
ClassDescriptor descriptor = mapping.getDescriptor();
Field referenceField = FieldUtils.getAllFieldsList(descriptor.getJavaClass())
.stream().filter(f -> f.getName().equals(mapping.getAttributeName()))
.findFirst().orElse(null);
if (SoftDelete.class.isAssignableFrom(mapping.getReferenceClass()) && referenceField != null) {
OneToOne oneToOne = referenceField.getAnnotation(OneToOne.class);
if (oneToOne != null && !Strings.isNullOrEmpty(oneToOne.mappedBy())) {
return new ExpressionBuilder().get("deleteTs").isNull();
}
}
return null;
}
示例16
private void setAdditionalCriteria(ClassDescriptor desc) {
Map<String, AdditionalCriteriaProvider> additionalCriteriaProviderMap = AppBeans.getAll(AdditionalCriteriaProvider.class);
StringBuilder criteriaBuilder = new StringBuilder();
additionalCriteriaProviderMap.values().stream()
.filter(item -> item.requiresAdditionalCriteria(desc.getJavaClass()))
.forEach(additionalCriteriaProvider ->
criteriaBuilder.append(additionalCriteriaProvider.getAdditionalCriteria(desc.getJavaClass())).append(" AND")
);
if (criteriaBuilder.length() != 0) {
String additionalCriteriaResult = criteriaBuilder.substring(0, criteriaBuilder.length() - 4);
desc.getQueryManager().setAdditionalCriteria(additionalCriteriaResult);
}
}
示例17
private void setCacheable(MetaClass metaClass, ClassDescriptor desc, Session session) {
String property = (String) session.getProperty("eclipselink.cache.shared.default");
boolean defaultCache = property == null || Boolean.valueOf(property);
if ((defaultCache && !desc.isIsolated())
|| desc.getCacheIsolation() == CacheIsolationType.SHARED
|| desc.getCacheIsolation() == CacheIsolationType.PROTECTED) {
metaClass.getAnnotations().put("cacheable", true);
desc.getCachePolicy().setCacheCoordinationType(CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS);
}
}
示例18
/**
* INTERNAL: Build the sequence definitions.
*/
protected HashSet<SequenceDefinition> buildSequenceDefinitions() {
// Remember the processed - to handle each sequence just once.
HashSet processedSequenceNames = new HashSet();
HashSet<SequenceDefinition> sequenceDefinitions = new HashSet<>();
for (ClassDescriptor descriptor : getSession().getDescriptors().values()) {
if (descriptor.usesSequenceNumbers()) {
String seqName = descriptor.getSequenceNumberName();
if (seqName == null) {
seqName = getSession().getDatasourcePlatform().getDefaultSequence().getName();
}
if (!processedSequenceNames.contains(seqName)) {
processedSequenceNames.add(seqName);
Sequence sequence = getSession().getDatasourcePlatform().getSequence(seqName);
SequenceDefinition sequenceDefinition = buildSequenceDefinition(sequence);
if (sequenceDefinition != null) {
sequenceDefinitions.add(sequenceDefinition);
}
}
}
}
return sequenceDefinitions;
}
示例19
@Override
protected void configure(ClassDescriptor descriptor, String... tableNames) {
DBRelationalDescriptor relationDescriptor = (DBRelationalDescriptor) descriptor;
// Configure Table names if provided
if (tableNames != null) {
if (tableNames.length == 0) {
//Fix for : https://github.com/jeddict/jeddict/issues/1
// If ClassDescriptor is entity then don't make it Aggregate
if (descriptor.getTables().size() == 0 && !(relationDescriptor.getAccessor() instanceof EntitySpecAccessor)) {
descriptor.descriptorIsAggregate();
}
} else {
for (int index = 0; index < tableNames.length; index++) {
descriptor.addTableName(tableNames[index]);
}
}
}
for (int index = 0; index < descriptor.getMappings().size(); index++) {
addMapping(descriptor.getMappings().get(index));
}
descriptor.setProperty(DynamicType.DESCRIPTOR_PROPERTY, entityType);
if (descriptor.getCMPPolicy() == null) {
descriptor.setCMPPolicy(new DynamicIdentityPolicy());
}
}
示例20
/**
* Checks class descriptors for {@link @RemoveMapping} and {@link RemoveMappings} annotations at the class level
* and removes any specified mappings from the ClassDescriptor.
*
* @param session the current session.
*/
protected void handleRemoveMapping(Session session) {
Map<Class, ClassDescriptor> descriptors = session.getDescriptors();
if (descriptors == null || descriptors.isEmpty()) {
return;
}
for (ClassDescriptor classDescriptor : descriptors.values()) {
List<DatabaseMapping> mappingsToRemove = new ArrayList<DatabaseMapping>();
List<RemoveMapping> removeMappings = scanForRemoveMappings(classDescriptor);
for (RemoveMapping removeMapping : removeMappings) {
if (StringUtils.isBlank(removeMapping.name())) {
throw DescriptorException.attributeNameNotSpecified();
}
DatabaseMapping databaseMapping = classDescriptor.getMappingForAttributeName(removeMapping.name());
if (databaseMapping == null) {
throw DescriptorException.mappingForAttributeIsMissing(removeMapping.name(), classDescriptor);
}
mappingsToRemove.add(databaseMapping);
}
for (DatabaseMapping mappingToRemove : mappingsToRemove) {
classDescriptor.removeMappingForAttributeName(mappingToRemove.getAttributeName());
}
}
}
示例21
@Test
public void testExtensionAttribute_eclipselink_data() {
ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
ClassDescriptor referenceDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObjectExtension.class);
assertNotNull("A classDescriptor should have been retrieved from JPA for TestDataObject", classDescriptor);
assertNotNull("A classDescriptor should have been retrieved from JPA for TestDataObjectExtension",
referenceDescriptor);
DatabaseMapping databaseMapping = classDescriptor.getMappingForAttributeName("extension");
assertNotNull("extension mapping missing from metamodel", databaseMapping);
assertTrue("Should be a OneToOne mapping", databaseMapping instanceof OneToOneMapping);
OneToOneMapping mapping = (OneToOneMapping)databaseMapping;
assertEquals("Should be mapped by primaryKeyProperty", "primaryKeyProperty", mapping.getMappedBy());
Map<DatabaseField, DatabaseField> databaseFields = mapping.getSourceToTargetKeyFields();
assertEquals(1, databaseFields.size());
for (DatabaseField sourceField : databaseFields.keySet()) {
DatabaseField targetField = databaseFields.get(sourceField);
assertEquals("PK_PROP", sourceField.getName());
assertEquals("PK_PROP", targetField.getName());
}
assertNotNull("Reference descriptor missing from relationship", mapping.getReferenceDescriptor());
assertEquals("Reference descriptor should be the one for TestDataObjectExtension", referenceDescriptor,
mapping.getReferenceDescriptor());
assertNotNull("selection query relationship missing", mapping.getSelectionQuery());
assertNotNull("selection query missing name", mapping.getSelectionQuery().getName());
assertEquals("selection query name incorrect", "extension", mapping.getSelectionQuery().getName());
assertNotNull("selection query reference class", mapping.getSelectionQuery().getReferenceClass());
assertEquals("selection query reference class incorrect", TestDataObjectExtension.class,
mapping.getSelectionQuery().getReferenceClass());
assertNotNull("selection query reference class name", mapping.getSelectionQuery().getReferenceClassName());
assertNotNull("selection query source mapping missing", mapping.getSelectionQuery().getSourceMapping());
assertEquals("selection query source mapping incorrect", mapping,
mapping.getSelectionQuery().getSourceMapping());
}
示例22
@Override
public CoreAttributeGroup cloneWithSameAttributes(Map<CoreAttributeGroup<AttributeItem, ClassDescriptor>, CoreAttributeGroup<AttributeItem, ClassDescriptor>> cloneMap) {
return new CubaEntityFetchGroup(wrappedFetchGroup.cloneWithSameAttributes());
}
示例23
@Override
public AttributeGroup findGroup(ClassDescriptor type) {
return wrappedFetchGroup.findGroup(type);
}
示例24
@Override
public CoreAttributeGroup clone(Map<CoreAttributeGroup<AttributeItem, ClassDescriptor>, CoreAttributeGroup<AttributeItem, ClassDescriptor>> cloneMap) {
return wrappedFetchGroup.clone(cloneMap);
}
示例25
private void setMultipleTableConstraintDependency(MetaClass metaClass, ClassDescriptor desc) {
InheritancePolicy policy = desc.getInheritancePolicyOrNull();
if (policy != null && policy.isJoinedStrategy() && policy.getParentClass() != null) {
desc.setHasMultipleTableConstraintDependecy(true);
}
}
示例26
/**
* Returns an ID of directly referenced entity without loading it from DB.
* <p>
* If the view does not contain the reference and {@link View#loadPartialEntities()} is true,
* the returned {@link RefId} will have {@link RefId#isLoaded()} = false.
*
* <p>Usage example:
* <pre>
* PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency");
* if (refId.isLoaded()) {
* String currencyCode = (String) refId.getValue();
* }
* </pre>
*
* @param entity entity instance in managed state
* @param property name of reference property
* @return {@link RefId} instance which contains the referenced entity ID
* @throws IllegalArgumentException if the specified property is not a reference
* @throws IllegalStateException if the entity is not in Managed state
* @throws RuntimeException if anything goes wrong when retrieving the ID
*/
public RefId getReferenceId(BaseGenericIdEntity entity, String property) {
MetaClass metaClass = metadata.getClassNN(entity.getClass());
MetaProperty metaProperty = metaClass.getPropertyNN(property);
if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany())
throw new IllegalArgumentException("Property is not a reference");
if (!entityStates.isManaged(entity))
throw new IllegalStateException("Entity must be in managed state");
String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity);
if (inaccessibleAttributes != null) {
for (String inaccessibleAttr : inaccessibleAttributes) {
if (inaccessibleAttr.equals(property))
return RefId.createNotLoaded(property);
}
}
if (entity instanceof FetchGroupTracker) {
FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup();
if (fetchGroup != null) {
if (!fetchGroup.containsAttributeInternal(property))
return RefId.createNotLoaded(property);
else {
Entity refEntity = (Entity) entity.getValue(property);
return RefId.create(property, refEntity == null ? null : refEntity.getId());
}
}
}
try {
Class<?> declaringClass = metaProperty.getDeclaringClass();
if (declaringClass == null) {
throw new RuntimeException("Property does not belong to persistent class");
}
Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property));
vhMethod.setAccessible(true);
ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity);
if (vh instanceof DatabaseValueHolder) {
AbstractRecord row = ((DatabaseValueHolder) vh).getRow();
if (row != null) {
Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class);
ClassDescriptor descriptor = session.getDescriptor(entity);
DatabaseMapping mapping = descriptor.getMappingForAttributeName(property);
Vector<DatabaseField> fields = mapping.getFields();
if (fields.size() != 1) {
throw new IllegalStateException("Invalid number of columns in mapping: " + fields);
}
Object value = row.get(fields.get(0));
if (value != null) {
ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass));
if (refMapping instanceof AbstractColumnMapping) {
Converter converter = ((AbstractColumnMapping) refMapping).getConverter();
if (converter != null) {
return RefId.create(property, converter.convertDataValueToObjectValue(value, session));
}
}
}
return RefId.create(property, value);
} else {
return RefId.create(property, null);
}
}
return RefId.createNotLoaded(property);
} catch (Exception e) {
throw new RuntimeException(
String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property),
e);
}
}
示例27
@BeforeEach
public void setUp() throws Exception {
assertTrue(cont.getSpringAppContext() == AppContext.getApplicationContext());
try (Transaction tx = cont.persistence().createTransaction()) {
EntityManagerFactory emf = cont.entityManager().getDelegate().getEntityManagerFactory();
assertTrue(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(User.class)));
assertFalse(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(UserSubstitution.class)));
ServerSession serverSession = ((EntityManagerFactoryDelegate) emf).getServerSession();
ClassDescriptor descriptor = serverSession.getDescriptor(User.class);
assertEquals(500, descriptor.getCachePolicy().getIdentityMapSize());
// assertTrue(Boolean.valueOf((String) emf.getProperties().get("eclipselink.cache.shared.default")));
// assertTrue(Boolean.valueOf((String) emf.getProperties().get("eclipselink.cache.shared.sec$User")));
this.cache = (JpaCache) emf.getCache();
group = cont.metadata().create(Group.class);
group.setName("group-" + group.getId());
cont.entityManager().persist(group);
user = cont.metadata().create(User.class);
user.setLogin("ECTest-" + user.getId());
user.setPassword("111");
user.setGroup(group);
cont.entityManager().persist(user);
user2 = cont.metadata().create(User.class);
user2.setLogin("ECTest-" + user2.getId());
user2.setPassword("111");
user2.setGroup(group);
cont.entityManager().persist(user2);
role = cont.metadata().create(Role.class);
role.setName("Test role");
role.setDescription("Test role descr");
cont.entityManager().persist(role);
userRole = cont.metadata().create(UserRole.class);
userRole.setRole(role);
userRole.setUser(user);
cont.entityManager().persist(userRole);
userSetting = cont.metadata().create(UserSetting.class);
userSetting.setUser(user);
cont.entityManager().persist(userSetting);
userSubstitution = cont.metadata().create(UserSubstitution.class);
userSubstitution.setUser(user);
userSubstitution.setSubstitutedUser(user2);
cont.entityManager().persist(userSubstitution);
compositeOne = cont.metadata().create(CompositeOne.class);
compositeOne.setName("compositeOne");
cont.entityManager().persist(compositeOne);
compositeTwo = cont.metadata().create(CompositeTwo.class);
compositeTwo.setName("compositeTwo");
cont.entityManager().persist(compositeTwo);
compositePropertyOne = cont.metadata().create(CompositePropertyOne.class);
compositePropertyOne.setName("compositePropertyOne");
compositePropertyOne.setCompositeOne(compositeOne);
compositePropertyOne.setCompositeTwo(compositeTwo);
cont.entityManager().persist(compositePropertyOne);
compositePropertyTwo = cont.metadata().create(CompositePropertyTwo.class);
compositePropertyTwo.setName("compositePropertyTwo");
compositePropertyTwo.setCompositeTwo(compositeTwo);
cont.entityManager().persist(compositePropertyTwo);
tx.commit();
}
cache.clear();
}
示例28
@BeforeEach
public void setUp() throws Exception {
assertTrue(cont.getSpringAppContext() == AppContext.getApplicationContext());
queryCache = AppBeans.get(QueryCache.NAME);
try (Transaction tx = cont.persistence().createTransaction()) {
EntityManagerFactory emf = cont.entityManager().getDelegate().getEntityManagerFactory();
assertTrue(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(User.class)));
assertFalse(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(UserSubstitution.class)));
ServerSession serverSession = ((EntityManagerFactoryDelegate) emf).getServerSession();
ClassDescriptor descriptor = serverSession.getDescriptor(User.class);
assertEquals(500, descriptor.getCachePolicy().getIdentityMapSize());
this.cache = (JpaCache) emf.getCache();
group = cont.metadata().create(Group.class);
group.setName("group-" + group.getId());
cont.entityManager().persist(group);
user = cont.metadata().create(User.class);
user.setLogin("ECTest-" + user.getId());
user.setPassword("111");
user.setName("1");
user.setGroup(group);
cont.entityManager().persist(user);
user2 = cont.metadata().create(User.class);
user2.setLogin("ECTest-" + user2.getId());
user2.setPassword("111");
user2.setName("2");
user2.setGroup(group);
cont.entityManager().persist(user2);
user3 = cont.metadata().create(User.class);
user3.setLogin("ECTest-" + user3.getId());
user3.setPassword("111");
user3.setGroup(group);
cont.entityManager().persist(user3);
role = cont.metadata().create(Role.class);
role.setName("TestRole");
role.setDescription("Test role descr");
cont.entityManager().persist(role);
userRole = cont.metadata().create(UserRole.class);
userRole.setRole(role);
userRole.setUser(user);
cont.entityManager().persist(userRole);
userSetting = cont.metadata().create(UserSetting.class);
userSetting.setUser(user);
cont.entityManager().persist(userSetting);
tx.commit();
}
try (Transaction tx = cont.persistence().createTransaction()) {
cont.entityManager().remove(user3);
tx.commit();
}
cache.clear();
queryCache.invalidateAll();
}
示例29
/**
*
* @param baseDescriptor
* @param intrinsicEntity defines the Entity Object that contains embedded
* Object where Entity object will be intrinsicEntity and Embeddable object
* will be descriptorManagedClass
* @param intrinsicAttribute
*/
protected void postInitTableSchema(ClassDescriptor baseDescriptor, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute) {
DBRelationalDescriptor descriptor = (DBRelationalDescriptor) baseDescriptor;
ManagedClass descriptorManagedClass = null;
if (intrinsicEntity == null) {
if (descriptor.getAccessor() instanceof EntitySpecAccessor) {
intrinsicEntity = new LinkedList<>();
intrinsicAttribute = new LinkedList<>();
intrinsicEntity.offer(((EntitySpecAccessor) descriptor.getAccessor()).getEntity());
descriptorManagedClass = intrinsicEntity.peek();
} else {
throw new IllegalStateException(descriptor.getAccessor() + " not supported");
}
} else if (descriptor.getAccessor() instanceof EmbeddableSpecAccessor) {
descriptorManagedClass = ((EmbeddableSpecAccessor) descriptor.getAccessor()).getEmbeddable();
} else if (descriptor.getAccessor() instanceof DefaultClassSpecAccessor) {
// descriptorManagedClass = ((DefaultClassSpecAccessor) descriptor.getAccessor()).getDefaultClass();
} else {
throw new IllegalStateException(descriptor.getAccessor() + " not supported");
}
for (DatabaseMapping mapping : descriptor.getMappings()) {
ManagedClass managedClass = descriptorManagedClass;
Attribute managedAttribute = (Attribute) mapping.getProperty(Attribute.class);
Boolean isInherited = (Boolean) mapping.getProperty(Inheritance.class);
isInherited = isInherited == null ? false : isInherited;
if (intrinsicAttribute.peek() == null) {
intrinsicAttribute.offer(managedAttribute);
}
if(managedAttribute instanceof RelationAttribute && !((RelationAttribute)managedAttribute).isOwner()){
//skip non-owner
} else if (descriptor.isChildDescriptor() && descriptor.getInheritancePolicy().getParentDescriptor().getMappingForAttributeName(mapping.getAttributeName()) != null) {
// If we are an inheritance subclass, do nothing. That is, don't
// generate mappings that will be generated by our parent,
// otherwise the fields for that mapping will be generated n
// times for the same table.
} else if (mapping.isManyToManyMapping()) {
buildRelationTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (ManyToManyMapping) mapping, ((ManyToManyMapping) mapping).getRelationTableMechanism(), ((ManyToManyMapping) mapping).getListOrderField(), mapping.getContainerPolicy());
} else if (mapping.isDirectCollectionMapping()) {
buildDirectCollectionTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (DirectCollectionMapping) mapping, descriptor);
} else if (mapping.isDirectToFieldMapping()) {
Converter converter = ((DirectToFieldMapping) mapping).getConverter();
if (converter != null) {
if (converter instanceof TypeConversionConverter) {
resetFieldTypeForLOB((DirectToFieldMapping) mapping);
}
// uncomment on upgrade to eclipselink v2.7.2+
// if (converter instanceof SerializedObjectConverter) {
// //serialized object mapping field should be BLOB/IMAGE
// getFieldDefFromDBField(mapping.getField()).setType(((SerializedObjectConverter) converter).getSerializer().getType());
// }
}
} else if (mapping.isAggregateCollectionMapping()) {
//need to figure out the target foreign key field and add it into the aggregate target table
// if(managedAttribute instanceof ElementCollection || ((ElementCollection)managedAttribute).getConnectedClass()!=null){
// ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
// Attribute attribute = getManagedAttribute(refDescriptor, dbField, intrinsicAttribute);//TODO intrinsicAttribute nested path/attribute not set
//
// }
createAggregateTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (AggregateCollectionMapping) mapping);
} else if (mapping.isForeignReferenceMapping()) {
if (mapping.isOneToOneMapping()) {
RelationTableMechanism relationTableMechanism = ((OneToOneMapping) mapping).getRelationTableMechanism();
if (relationTableMechanism == null) {
addForeignKeyFieldToSourceTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToOneMapping) mapping);
} else {
buildRelationTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToOneMapping) mapping, relationTableMechanism, null, null);
}
} else if (mapping.isOneToManyMapping()) {
addForeignKeyFieldToSourceTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToManyMapping) mapping);
TableDefinition targTblDef = getTableDefFromDBTable(((OneToManyMapping) mapping).getReferenceDescriptor().getDefaultTable());//TODO pass entity
addFieldsForMappedKeyMapContainerPolicy(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, mapping.getContainerPolicy(), targTblDef);
}
} else if (mapping.isTransformationMapping()) {
resetTransformedFieldType((TransformationMapping) mapping);
} else if (mapping.isAggregateObjectMapping()) {
postInitTableSchema(((AggregateObjectMapping) mapping).getReferenceDescriptor(), new LinkedList<>(intrinsicEntity), new LinkedList<>(intrinsicAttribute));
}
intrinsicAttribute.clear();
}
processAdditionalTablePkFields(intrinsicEntity, descriptor);
intrinsicEntity.clear();
}
示例30
public JPAMDynamicTypeBuilder(DynamicClassLoader dcl, ClassDescriptor descriptor, DynamicType parentType) {
super(dcl, descriptor, parentType);
}