use of org.hibernate.metadata.ClassMetadata in project candlepin by candlepin.
the class AbstractHibernateCurator method lockAndLoadById.
/**
* Loads an entity with a pessimistic lock using the specified entity class and ID. If the
* entity has already been loaded, it will be refreshed with the lock instead. If a matching
* entity could not be found, this method returns null.
*
* @param entityClass
* The class representing the type of entity to fetch (i.e. Pool.class or Product.class)
*
* @param id
* The id of the entity to load/refresh and lock
*
* @return
* A locked entity instance, or null if a matching entity could not be found
*/
@SuppressWarnings("unchecked")
protected E lockAndLoadById(Class<E> entityClass, Serializable id) {
EntityManager entityManager = this.getEntityManager();
SessionImpl session = (SessionImpl) this.currentSession();
ClassMetadata metadata = session.getFactory().getClassMetadata(entityClass);
// and check if it's already in the session cache without doing a database lookup
if (metadata == null || !metadata.hasIdentifierProperty()) {
throw new UnsupportedOperationException("lockAndLoad only supports entities with database identifiers");
}
// Fetch the entity persister and session context so we can check the session cache for an
// entity before hitting the database.
EntityPersister persister = session.getFactory().getEntityPersister(metadata.getEntityName());
PersistenceContext context = session.getPersistenceContext();
// Lookup whether or not we have an entity with a given ID in the current session's cache.
// See the notes in lockAndLoadByIds for details as to why we're going about it this way.
EntityKey key = session.generateEntityKey(id, persister);
E entity = (E) context.getEntity(key);
if (entity == null) {
// The entity isn't in the local session, we'll need to query for it
String idName = metadata.getIdentifierPropertyName();
if (idName == null) {
// This shouldn't happen.
throw new RuntimeException("Unable to fetch identifier property name");
}
// Impl note:
// We're building the query here using JPA Criteria to avoid fiddling with string
// building and, potentially, erroneously using the class name as the entity name.
// Additionally, using a query (as opposed to the .find and .load methods) lets us set
// the flush, cache and lock modes for the entity we're attempting to fetch.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<E> query = builder.createQuery(entityClass);
Root<E> root = query.from(entityClass);
Path<Serializable> target = root.<Serializable>get(idName);
ParameterExpression<Serializable> param = builder.parameter(Serializable.class);
query.select(root).where(builder.equal(target, param));
// by Hibernate down to a CacheMode.REFRESH.
try {
entity = entityManager.createQuery(query).setFlushMode(FlushModeType.COMMIT).setHint(AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS).setHint(AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH).setLockMode(LockModeType.PESSIMISTIC_WRITE).setParameter(param, id).getSingleResult();
} catch (NoResultException exception) {
// No entity found matching the ID. We don't define this as an error case, so we're
// going to silently discard the exception.
}
} else {
// It's already available locally. Issue a refresh with a lock.
entityManager.refresh(entity, LockModeType.PESSIMISTIC_WRITE);
}
return entity;
}
use of org.hibernate.metadata.ClassMetadata in project jbosstools-hibernate by jbosstools.
the class ClassMetadataFacadeTest method setUp.
@Before
public void setUp() {
ClassMetadata target = (ClassMetadata) Proxy.newProxyInstance(FACADE_FACTORY.getClassLoader(), new Class[] { ClassMetadata.class }, new TestInvocationHandler());
classMetadata = new ClassMetadataFacadeImpl(FACADE_FACTORY, target);
}
use of org.hibernate.metadata.ClassMetadata in project uPortal by Jasig.
the class PortalRawEventsAggregatorImpl method getCollectionRoles.
private List<String> getCollectionRoles(final SessionFactory sessionFactory, final Class<?> entityClass) {
List<String> collectionRoles = entityCollectionRoles.get(entityClass);
if (collectionRoles != null) {
return collectionRoles;
}
final com.google.common.collect.ImmutableList.Builder<String> collectionRolesBuilder = ImmutableList.builder();
final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
for (final Type type : classMetadata.getPropertyTypes()) {
if (type.isCollectionType()) {
collectionRolesBuilder.add(((CollectionType) type).getRole());
}
}
collectionRoles = collectionRolesBuilder.build();
entityCollectionRoles.put(entityClass, collectionRoles);
return collectionRoles;
}
use of org.hibernate.metadata.ClassMetadata in project scheduling by ow2-proactive.
the class TestJobRemove method checkAllEntitiesDeleted.
private void checkAllEntitiesDeleted(String... skipClasses) {
Set<String> skip = ImmutableSet.copyOf(skipClasses);
Session session = dbManager.getSessionFactory().openSession();
try {
for (ClassMetadata metadata : session.getSessionFactory().getAllClassMetadata().values()) {
if (!skip.contains(metadata.getEntityName())) {
System.out.println("Check " + metadata.getEntityName());
List<Object> list = session.createCriteria(metadata.getEntityName()).list();
Assert.assertEquals("Unexpected " + metadata.getEntityName(), 0, list.size());
}
}
} finally {
session.close();
}
}
use of org.hibernate.metadata.ClassMetadata in project mycore by MyCoRe-Org.
the class MCRHibernateConfigHelper method modifyConstraints.
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) {
ClassMetadata classMetadata = sessionFactoryImpl.getClassMetadata(MCRCategoryImpl.class);
AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata;
String qualifiedTableName = aep.getTableName();
try (Session session = sessionFactoryImpl.openSession()) {
session.doWork(connection -> {
String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique").flatMap(idx -> Stream.of("drop constraint if exists " + idx, MessageFormat.format("add constraint {0} unique ({1}) deferrable initially deferred", idx, getUniqueColumns(MCRCategoryImpl.class, idx)))).collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", ""));
try (Statement stmt = connection.createStatement()) {
LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt);
stmt.execute(updateStmt);
}
});
}
}
Aggregations