use of org.eclipse.persistence.descriptors.ClassDescriptor in project cuba by cuba-platform.
the class PersistenceTools method getReferenceId.
/**
* Returns an ID of directly referenced entity without loading it from DB.
*
* 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 (!PersistenceHelper.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.getAttributeNames().contains(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);
}
}
use of org.eclipse.persistence.descriptors.ClassDescriptor in project cuba by cuba-platform.
the class EclipseLinkSessionEventListener method preLogin.
@Override
public void preLogin(SessionEvent event) {
Session session = event.getSession();
setPrintInnerJoinOnClause(session);
Map<Class, ClassDescriptor> descriptorMap = session.getDescriptors();
for (Map.Entry<Class, ClassDescriptor> entry : descriptorMap.entrySet()) {
MetaClass metaClass = metadata.getSession().getClassNN(entry.getKey());
ClassDescriptor desc = entry.getValue();
setCacheable(metaClass, desc, session);
if (Entity.class.isAssignableFrom(desc.getJavaClass())) {
// set DescriptorEventManager that doesn't invoke listeners for base classes
desc.setEventManager(new DescriptorEventManager() {
@Override
public void notifyListeners(DescriptorEvent event) {
if (hasAnyListeners()) {
for (int index = 0; index < getEventListeners().size(); index++) {
DescriptorEventListener listener = (DescriptorEventListener) getEventListeners().get(index);
notifyListener(listener, event);
}
}
}
});
desc.getEventManager().addListener(descriptorEventListener);
}
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();
for (DatabaseMapping mapping : mappings) {
// support UUID
String attributeName = mapping.getAttributeName();
MetaProperty metaProperty = metaClass.getPropertyNN(attributeName);
if (metaProperty.getRange().isDatatype()) {
if (metaProperty.getJavaType().equals(UUID.class)) {
((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
setDatabaseFieldParameters(session, mapping.getField());
}
} else if (metaProperty.getRange().isClass() && !metaProperty.getRange().getCardinality().isMany()) {
MetaClass refMetaClass = metaProperty.getRange().asClass();
MetaProperty refPkProperty = metadata.getTools().getPrimaryKeyProperty(refMetaClass);
if (refPkProperty != null && refPkProperty.getJavaType().equals(UUID.class)) {
for (DatabaseField field : ((OneToOneMapping) mapping).getForeignKeyFields()) {
setDatabaseFieldParameters(session, field);
}
}
}
// embedded attributes
if (mapping instanceof AggregateObjectMapping) {
EmbeddedParameters embeddedParameters = metaProperty.getAnnotatedElement().getAnnotation(EmbeddedParameters.class);
if (embeddedParameters != null && !embeddedParameters.nullAllowed())
((AggregateObjectMapping) mapping).setIsNullAllowed(false);
}
if (mapping.isOneToManyMapping()) {
OneToManyMapping oneToManyMapping = (OneToManyMapping) mapping;
if (SoftDelete.class.isAssignableFrom(oneToManyMapping.getReferenceClass())) {
oneToManyMapping.setAdditionalJoinCriteria(new ExpressionBuilder().get("deleteTs").isNull());
}
}
if (mapping.isOneToOneMapping()) {
OneToOneMapping oneToOneMapping = (OneToOneMapping) mapping;
if (SoftDelete.class.isAssignableFrom(oneToOneMapping.getReferenceClass())) {
if (mapping.isManyToOneMapping()) {
oneToOneMapping.setSoftDeletionForBatch(false);
oneToOneMapping.setSoftDeletionForValueHolder(false);
} else {
OneToOne oneToOne = metaProperty.getAnnotatedElement().getAnnotation(OneToOne.class);
if (oneToOne != null) {
if (Strings.isNullOrEmpty(oneToOne.mappedBy())) {
oneToOneMapping.setSoftDeletionForBatch(false);
oneToOneMapping.setSoftDeletionForValueHolder(false);
} else {
oneToOneMapping.setAdditionalJoinCriteria(new ExpressionBuilder().get("deleteTs").isNull());
}
}
}
}
}
}
}
}
use of org.eclipse.persistence.descriptors.ClassDescriptor in project cuba by cuba-platform.
the class EntityCacheTestClass method setUp.
@Before
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);
tx.commit();
}
cache.clear();
}
use of org.eclipse.persistence.descriptors.ClassDescriptor in project cuba by cuba-platform.
the class QueryCacheTestClass method setUp.
@Before
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();
}
use of org.eclipse.persistence.descriptors.ClassDescriptor in project tomee by apache.
the class PrefixSessionCustomizer method customize.
@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());
}
}
}
Aggregations