Search in sources :

Example 36 with ClassMetadata

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;
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) EntityPersister(org.hibernate.persister.entity.EntityPersister) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Serializable(java.io.Serializable) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) NoResultException(javax.persistence.NoResultException) EntityKey(org.hibernate.engine.spi.EntityKey) EntityManager(javax.persistence.EntityManager) SessionImpl(org.hibernate.internal.SessionImpl)

Example 37 with ClassMetadata

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);
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) IClassMetadata(org.jboss.tools.hibernate.runtime.spi.IClassMetadata) RootClass(org.hibernate.mapping.RootClass) PersistentClass(org.hibernate.mapping.PersistentClass) Before(org.junit.Before)

Example 38 with ClassMetadata

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;
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) CollectionType(org.hibernate.type.CollectionType) FlushModeType(javax.persistence.FlushModeType) Type(org.hibernate.type.Type) ImmutableList(com.google.common.collect.ImmutableList)

Example 39 with ClassMetadata

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();
    }
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) Session(org.hibernate.Session)

Example 40 with ClassMetadata

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);
            }
        });
    }
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) Connection(java.sql.Connection) UniqueConstraint(javax.persistence.UniqueConstraint) Session(org.hibernate.Session) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) Collectors(java.util.stream.Collectors) MessageFormat(java.text.MessageFormat) ClassMetadata(org.hibernate.metadata.ClassMetadata) SQLException(java.sql.SQLException) Stream(java.util.stream.Stream) Table(javax.persistence.Table) PostgreSQL9Dialect(org.hibernate.dialect.PostgreSQL9Dialect) PersistenceException(javax.persistence.PersistenceException) EntityManagerFactory(javax.persistence.EntityManagerFactory) Statement(java.sql.Statement) Optional(java.util.Optional) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) MCRCategoryImpl(org.mycore.datamodel.classifications2.impl.MCRCategoryImpl) SessionFactoryImpl(org.hibernate.internal.SessionFactoryImpl) LogManager(org.apache.logging.log4j.LogManager) Statement(java.sql.Statement) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) Session(org.hibernate.Session)

Aggregations

ClassMetadata (org.hibernate.metadata.ClassMetadata)58 PersistentClass (org.hibernate.mapping.PersistentClass)23 IClassMetadata (org.jboss.tools.hibernate.runtime.spi.IClassMetadata)21 RootClass (org.hibernate.mapping.RootClass)20 IPOJOClass (org.jboss.tools.hibernate.runtime.spi.IPOJOClass)12 IPersistentClass (org.jboss.tools.hibernate.runtime.spi.IPersistentClass)12 POJOClass (org.hibernate.tool.hbm2x.pojo.POJOClass)11 Test (org.junit.jupiter.api.Test)11 Type (org.hibernate.type.Type)10 Before (org.junit.Before)8 Field (java.lang.reflect.Field)5 AbstractEntityPersister (org.hibernate.persister.entity.AbstractEntityPersister)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 Session (org.hibernate.Session)4 SessionFactory (org.hibernate.SessionFactory)4 SessionImpl (org.hibernate.internal.SessionImpl)4 ComponentType (org.hibernate.type.ComponentType)4 AbstractClassMetadataFacade (org.jboss.tools.hibernate.runtime.common.AbstractClassMetadataFacade)4 MasterDataEntity (org.mifos.application.master.business.MasterDataEntity)4