Search in sources :

Example 61 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class NaturalIdInvalidationTest method testAll.

@Test
public void testAll() throws Exception {
    log.info("*** testAll()");
    // Bind a listener to the "local" cache
    // Our region factory makes its CacheManager available to us
    CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTest.LOCAL);
    Cache localNaturalIdCache = localManager.getCache(Citizen.class.getName() + "##NaturalId");
    MyListener localListener = new MyListener("local");
    localNaturalIdCache.addListener(localListener);
    // Bind a listener to the "remote" cache
    CacheContainer remoteManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTest.REMOTE);
    Cache remoteNaturalIdCache = remoteManager.getCache(Citizen.class.getName() + "##NaturalId");
    MyListener remoteListener = new MyListener("remote");
    remoteNaturalIdCache.addListener(remoteListener);
    SessionFactory localFactory = sessionFactory();
    SessionFactory remoteFactory = secondNodeEnvironment().getSessionFactory();
    try {
        assertTrue(remoteListener.isEmpty());
        assertTrue(localListener.isEmpty());
        CountDownLatch remoteUpdateLatch = expectAfterUpdate(remoteNaturalIdCache.getAdvancedCache(), 2);
        saveSomeCitizens(localFactory);
        assertTrue(remoteUpdateLatch.await(2, TimeUnit.SECONDS));
        assertTrue(remoteListener.isEmpty());
        assertTrue(localListener.isEmpty());
        log.debug("Find node 0");
        // This actually brings the collection into the cache
        getCitizenWithCriteria(localFactory);
        // Now the collection is in the cache so, the 2nd "get"
        // should read everything from the cache
        log.debug("Find(2) node 0");
        localListener.clear();
        getCitizenWithCriteria(localFactory);
        // Check the read came from the cache
        log.debug("Check cache 0");
        assertLoadedFromCache(localListener, "1234");
        log.debug("Find node 1");
        // This actually brings the collection into the cache since invalidation is in use
        getCitizenWithCriteria(remoteFactory);
        // Now the collection is in the cache so, the 2nd "get"
        // should read everything from the cache
        log.debug("Find(2) node 1");
        remoteListener.clear();
        getCitizenWithCriteria(remoteFactory);
        // Check the read came from the cache
        log.debug("Check cache 1");
        assertLoadedFromCache(remoteListener, "1234");
        // Modify customer in remote
        remoteListener.clear();
        CountDownLatch localUpdate = expectEvict(localNaturalIdCache.getAdvancedCache(), 1);
        deleteCitizenWithCriteria(remoteFactory);
        assertTrue(localUpdate.await(2, TimeUnit.SECONDS));
        Set localKeys = localNaturalIdCache.keySet();
        assertEquals(1, localKeys.size());
        // Only key left is the one for the citizen *not* in France
        localKeys.toString().contains("000");
    } catch (Exception e) {
        log.error("Error", e);
        throw e;
    } finally {
        withTxSession(localFactory, s -> {
            s.createQuery("delete NaturalIdOnManyToOne").executeUpdate();
            s.createQuery("delete Citizen").executeUpdate();
            s.createQuery("delete State").executeUpdate();
        });
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) ConcurrentSet(org.jboss.util.collection.ConcurrentSet) Set(java.util.Set) CacheContainer(org.infinispan.manager.CacheContainer) CountDownLatch(java.util.concurrent.CountDownLatch) Cache(org.infinispan.Cache) Test(org.junit.Test)

Example 62 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class QueryRegionImplTest method testPutDoesNotBlockGet.

@Test
public void testPutDoesNotBlockGet() throws Exception {
    withQueryRegion((sessionFactory, region) -> {
        withSession(sessionFactory, session -> region.put(session, KEY, VALUE1));
        assertEquals(VALUE1, callWithSession(sessionFactory, session -> region.get(session, KEY)));
        final CountDownLatch readerLatch = new CountDownLatch(1);
        final CountDownLatch writerLatch = new CountDownLatch(1);
        final CountDownLatch completionLatch = new CountDownLatch(1);
        final ExceptionHolder holder = new ExceptionHolder();
        Thread reader = new Thread() {

            @Override
            public void run() {
                try {
                    assertNotEquals(VALUE2, callWithSession(sessionFactory, session -> region.get(session, KEY)));
                } catch (AssertionFailedError e) {
                    holder.addAssertionFailure(e);
                } catch (Exception e) {
                    holder.addException(e);
                } finally {
                    readerLatch.countDown();
                }
            }
        };
        Thread writer = new Thread() {

            @Override
            public void run() {
                try {
                    withSession(sessionFactory, session -> {
                        region.put(session, KEY, VALUE2);
                        writerLatch.await();
                    });
                } catch (Exception e) {
                    holder.addException(e);
                } finally {
                    completionLatch.countDown();
                }
            }
        };
        reader.setDaemon(true);
        writer.setDaemon(true);
        writer.start();
        assertFalse("Writer is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS));
        // Start the reader
        reader.start();
        assertTrue("Reader finished promptly", readerLatch.await(100, TimeUnit.MILLISECONDS));
        writerLatch.countDown();
        assertTrue("Reader finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS));
        assertEquals(VALUE2, callWithSession(sessionFactory, session -> region.get(session, KEY)));
    });
}
Also used : InfinispanRegionFactory(org.hibernate.cache.infinispan.InfinispanRegionFactory) QueryResultsRegionImpl(org.hibernate.cache.infinispan.query.QueryResultsRegionImpl) Logger(org.jboss.logging.Logger) CacheEntryModifiedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent) CacheEntryVisitedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent) Session(org.hibernate.Session) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) QueryResultsRegion(org.hibernate.cache.spi.QueryResultsRegion) ArrayList(java.util.ArrayList) Transaction(org.hibernate.Transaction) TestForIssue(org.hibernate.testing.TestForIssue) CacheEntryVisited(org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited) AdvancedCache(org.infinispan.AdvancedCache) CacheEntryModified(org.infinispan.notifications.cachelistener.annotation.CacheEntryModified) CyclicBarrier(java.util.concurrent.CyclicBarrier) Properties(java.util.Properties) Listener(org.infinispan.notifications.Listener) SessionFactory(org.hibernate.SessionFactory) CacheTestUtil(org.hibernate.test.cache.infinispan.util.CacheTestUtil) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AssertionFailedError(junit.framework.AssertionFailedError) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) StandardQueryCache(org.hibernate.cache.internal.StandardQueryCache) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CacheDataDescription(org.hibernate.cache.spi.CacheDataDescription) IsolationLevel(org.infinispan.util.concurrent.IsolationLevel) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) Region(org.hibernate.cache.spi.Region) AbstractGeneralDataRegionTest(org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CountDownLatch(java.util.concurrent.CountDownLatch) AssertionFailedError(junit.framework.AssertionFailedError) Test(org.junit.Test) AbstractGeneralDataRegionTest(org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTest)

Example 63 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class DropSchemaDuringJtaTxnTest method testDrop.

@Test
public void testDrop() throws Exception {
    final SessionFactory sessionFactory = buildSessionFactory();
    sessionFactory.close();
}
Also used : SessionFactory(org.hibernate.SessionFactory) Test(org.junit.Test)

Example 64 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class HibernateUtil method getSessionFactory.

private SessionFactory getSessionFactory() {
    if (sf == null) {
        Bundle thisBundle = FrameworkUtil.getBundle(HibernateUtil.class);
        // Could get this by wiring up OsgiTestBundleActivator as well.
        BundleContext context = thisBundle.getBundleContext();
        ServiceReference sr = context.getServiceReference(SessionFactory.class.getName());
        sf = (SessionFactory) context.getService(sr);
    }
    return sf;
}
Also used : SessionFactory(org.hibernate.SessionFactory) Bundle(org.osgi.framework.Bundle) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference)

Example 65 with SessionFactory

use of org.hibernate.SessionFactory in project hibernate-orm by hibernate.

the class SessionFactoryRegistry method getSessionFactory.

public SessionFactory getSessionFactory(String uuid) {
    LOG.debugf("Lookup: uid=%s", uuid);
    final SessionFactory sessionFactory = sessionFactoryMap.get(uuid);
    if (sessionFactory == null && LOG.isDebugEnabled()) {
        LOG.debugf("Not found: %s", uuid);
        LOG.debugf(sessionFactoryMap.toString());
    }
    return sessionFactory;
}
Also used : SessionFactory(org.hibernate.SessionFactory)

Aggregations

SessionFactory (org.hibernate.SessionFactory)108 Test (org.junit.Test)62 Session (org.hibernate.Session)50 Configuration (org.hibernate.cfg.Configuration)35 Transaction (org.hibernate.Transaction)20 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)19 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)13 MetadataSources (org.hibernate.boot.MetadataSources)11 HibernateEntityManagerFactory (org.hibernate.jpa.HibernateEntityManagerFactory)9 TestForIssue (org.hibernate.testing.TestForIssue)9 Properties (java.util.Properties)8 Query (org.hibernate.Query)8 Metadata (org.hibernate.boot.Metadata)8 ArrayList (java.util.ArrayList)7 InfinispanRegionFactory (org.hibernate.cache.infinispan.InfinispanRegionFactory)7 List (java.util.List)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 TimeUnit (java.util.concurrent.TimeUnit)5 AnnotationException (org.hibernate.AnnotationException)5 Collections (java.util.Collections)4