Search in sources :

Example 6 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class CorrectnessTestCase method checkForEmptyPendingPuts.

protected void checkForEmptyPendingPuts() throws Exception {
    Field pp = PutFromLoadValidator.class.getDeclaredField("pendingPuts");
    pp.setAccessible(true);
    Method getInvalidators = null;
    List<DelayedInvalidators> delayed = new LinkedList<>();
    for (int i = 0; i < sessionFactories.length; i++) {
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactories[i];
        for (Object regionName : sfi.getCache().getSecondLevelCacheRegionNames()) {
            PutFromLoadValidator validator = getPutFromLoadValidator(sfi, (String) regionName);
            if (validator == null) {
                log.warn("No validator for " + regionName);
                continue;
            }
            ConcurrentMap<Object, Object> map = (ConcurrentMap) pp.get(validator);
            for (Iterator<Map.Entry<Object, Object>> iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry entry = iterator.next();
                if (getInvalidators == null) {
                    getInvalidators = entry.getValue().getClass().getMethod("getInvalidators");
                    getInvalidators.setAccessible(true);
                }
                java.util.Collection invalidators = (java.util.Collection) getInvalidators.invoke(entry.getValue());
                if (invalidators != null && !invalidators.isEmpty()) {
                    delayed.add(new DelayedInvalidators(map, entry.getKey()));
                }
            }
        }
    }
    // poll until all invalidations come
    long deadline = System.currentTimeMillis() + 30000;
    while (System.currentTimeMillis() < deadline) {
        iterateInvalidators(delayed, getInvalidators, (k, i) -> {
        });
        if (delayed.isEmpty()) {
            break;
        }
        Thread.sleep(1000);
    }
    if (!delayed.isEmpty()) {
        iterateInvalidators(delayed, getInvalidators, (k, i) -> log.warnf("Left invalidators on key %s: %s", k, i));
        throw new IllegalStateException("Invalidators were not cleared: " + delayed.size());
    }
}
Also used : PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) ConcurrentMap(java.util.concurrent.ConcurrentMap) Method(java.lang.reflect.Method) LinkedList(java.util.LinkedList) Field(java.lang.reflect.Field) Collection(org.hibernate.mapping.Collection) Map(java.util.Map) TreeMap(java.util.TreeMap) NavigableMap(java.util.NavigableMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap)

Example 7 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project spring-framework by spring-projects.

the class SessionFactoryUtils method getDataSource.

/**
	 * Determine the DataSource of the given SessionFactory.
	 * @param sessionFactory the SessionFactory to check
	 * @return the DataSource, or {@code null} if none found
	 * @see ConnectionProvider
	 */
public static DataSource getDataSource(SessionFactory sessionFactory) {
    Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
    if (getProperties != null) {
        Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
        Object dataSourceValue = props.get(Environment.DATASOURCE);
        if (dataSourceValue instanceof DataSource) {
            return (DataSource) dataSourceValue;
        }
    }
    if (sessionFactory instanceof SessionFactoryImplementor) {
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
        try {
            ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
            if (cp != null) {
                return cp.unwrap(DataSource.class);
            }
        } catch (UnknownServiceException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
            }
        }
    }
    return null;
}
Also used : SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) UnknownServiceException(org.hibernate.service.UnknownServiceException) Method(java.lang.reflect.Method) Map(java.util.Map) DataSource(javax.sql.DataSource) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider)

Example 8 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class ListenerTest method testLoadListener.

@Test(expected = SecurityException.class)
public void testLoadListener() {
    Serializable customerId = 1L;
    doInJPA(this::entityManagerFactory, entityManager -> {
        EntityManagerFactory entityManagerFactory = entityManagerFactory();
        SessionFactoryImplementor sessionFactory = entityManagerFactory.unwrap(SessionFactoryImplementor.class);
        sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class).prependListeners(EventType.LOAD, new SecuredLoadEntityListener());
        Customer customer = entityManager.find(Customer.class, customerId);
    });
}
Also used : Serializable(java.io.Serializable) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityManagerFactory(javax.persistence.EntityManagerFactory) EventListenerRegistry(org.hibernate.event.service.spi.EventListenerRegistry) Test(org.junit.Test)

Example 9 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class EntityInsertAction method execute.

@Override
public void execute() throws HibernateException {
    nullifyTransientReferencesIfNotAlready();
    final EntityPersister persister = getPersister();
    final SharedSessionContractImplementor session = getSession();
    final Object instance = getInstance();
    final Serializable id = getId();
    final boolean veto = preInsert();
    if (!veto) {
        persister.insert(id, getState(), instance, session);
        PersistenceContext persistenceContext = session.getPersistenceContext();
        final EntityEntry entry = persistenceContext.getEntry(instance);
        if (entry == null) {
            throw new AssertionFailure("possible non-threadsafe access to session");
        }
        entry.postInsert(getState());
        if (persister.hasInsertGeneratedProperties()) {
            persister.processInsertGeneratedProperties(id, instance, getState(), session);
            if (persister.isVersionPropertyGenerated()) {
                version = Versioning.getVersion(getState(), persister);
            }
            entry.postUpdate(instance, getState(), version);
        }
        persistenceContext.registerInsertedKey(persister, getId());
    }
    final SessionFactoryImplementor factory = session.getFactory();
    if (isCachePutEnabled(persister, session)) {
        final CacheEntry ce = persister.buildCacheEntry(instance, getState(), version, session);
        cacheEntry = persister.getCacheEntryStructure().structure(ce);
        final EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
        final Object ck = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
        final boolean put = cacheInsert(persister, ck);
        if (put && factory.getStatistics().isStatisticsEnabled()) {
            factory.getStatistics().secondLevelCachePut(cache.getRegion().getName());
        }
    }
    handleNaturalIdPostSaveNotifications(id);
    postInsert();
    if (factory.getStatistics().isStatisticsEnabled() && !veto) {
        factory.getStatistics().insertEntity(getPersister().getEntityName());
    }
    markExecuted();
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) EntityEntry(org.hibernate.engine.spi.EntityEntry) AssertionFailure(org.hibernate.AssertionFailure) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry)

Example 10 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class Helper method openTemporarySessionForLoading.

private SharedSessionContractImplementor openTemporarySessionForLoading(LazyInitializationWork lazyInitializationWork) {
    if (consumer.getSessionFactoryUuid() == null) {
        throwLazyInitializationException(Cause.NO_SF_UUID, lazyInitializationWork);
    }
    final SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(consumer.getSessionFactoryUuid());
    final SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
    session.getPersistenceContext().setDefaultReadOnly(true);
    session.setHibernateFlushMode(FlushMode.MANUAL);
    return session;
}
Also used : SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor)

Aggregations

SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)129 Test (org.junit.Test)46 Configuration (org.hibernate.cfg.Configuration)27 SQLException (java.sql.SQLException)18 Type (org.hibernate.type.Type)16 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Connection (java.sql.Connection)12 HibernateException (org.hibernate.HibernateException)12 PreparedStatement (java.sql.PreparedStatement)11 Metadata (org.hibernate.boot.Metadata)11 Statement (java.sql.Statement)10 ArrayList (java.util.ArrayList)10 JdbcConnectionAccess (org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess)10 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)10 Serializable (java.io.Serializable)9 EncapsulatedCompositeIdResultSetProcessorTest (org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)8 HashMap (java.util.HashMap)7 Integrator (org.hibernate.integrator.spi.Integrator)7 SessionFactoryServiceRegistry (org.hibernate.service.spi.SessionFactoryServiceRegistry)7 Map (java.util.Map)6