Search in sources :

Example 6 with SessionFactory

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

the class EntityCollectionInvalidationTest method createCustomer.

private IdContainer createCustomer(SessionFactory sessionFactory) throws Exception {
    log.debug("CREATE CUSTOMER");
    Customer customer = new Customer();
    customer.setName("JBoss");
    Set<Contact> contacts = new HashSet<Contact>();
    Contact kabir = new Contact();
    kabir.setCustomer(customer);
    kabir.setName("Kabir");
    kabir.setTlf("1111");
    contacts.add(kabir);
    Contact bill = new Contact();
    bill.setCustomer(customer);
    bill.setName("Bill");
    bill.setTlf("2222");
    contacts.add(bill);
    customer.setContacts(contacts);
    ArrayList<Runnable> cleanup = new ArrayList<>();
    CountDownLatch customerLatch = new CountDownLatch(1);
    CountDownLatch collectionLatch = new CountDownLatch(1);
    CountDownLatch contactsLatch = new CountDownLatch(2);
    if (cacheMode.isInvalidation()) {
        cleanup.add(mockValidator(remoteCustomerCache, customerLatch));
        cleanup.add(mockValidator(remoteCollectionCache, collectionLatch));
        cleanup.add(mockValidator(remoteContactCache, contactsLatch));
    } else if (accessType == AccessType.NONSTRICT_READ_WRITE) {
        // ATM nonstrict mode has sync after-invalidation update
        Stream.of(customerLatch, collectionLatch, contactsLatch, contactsLatch).forEach(l -> l.countDown());
    } else {
        ExpectingInterceptor.get(remoteCustomerCache).when(this::isFutureUpdate).countDown(collectionLatch);
        ExpectingInterceptor.get(remoteCollectionCache).when(this::isFutureUpdate).countDown(customerLatch);
        ExpectingInterceptor.get(remoteContactCache).when(this::isFutureUpdate).countDown(contactsLatch);
        cleanup.add(() -> ExpectingInterceptor.cleanup(remoteCustomerCache, remoteCollectionCache, remoteContactCache));
    }
    withTxSession(sessionFactory, session -> session.save(customer));
    assertTrue(customerLatch.await(2, TimeUnit.SECONDS));
    assertTrue(collectionLatch.await(2, TimeUnit.SECONDS));
    assertTrue(contactsLatch.await(2, TimeUnit.SECONDS));
    cleanup.forEach(Runnable::run);
    IdContainer ids = new IdContainer();
    ids.customerId = customer.getId();
    Set contactIds = new HashSet();
    contactIds.add(kabir.getId());
    contactIds.add(bill.getId());
    ids.contactIds = contactIds;
    log.debug("CREATE CUSTOMER -  END");
    return ids;
}
Also used : ConcurrentSet(org.jboss.util.collection.ConcurrentSet) InfinispanRegionFactory(org.hibernate.cache.infinispan.InfinispanRegionFactory) CacheEntryVisitedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent) TimeoutException(java.util.concurrent.TimeoutException) Session(org.hibernate.Session) Cache(org.infinispan.Cache) Mockito.spy(org.mockito.Mockito.spy) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BiPredicate(java.util.function.BiPredicate) TestForIssue(org.hibernate.testing.TestForIssue) InvocationContext(org.infinispan.context.InvocationContext) CacheEntryVisited(org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited) AdvancedCache(org.infinispan.AdvancedCache) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ExpectingInterceptor(org.hibernate.test.cache.infinispan.util.ExpectingInterceptor) AccessType(org.hibernate.cache.spi.access.AccessType) GetKeyValueCommand(org.infinispan.commands.read.GetKeyValueCommand) Listener(org.infinispan.notifications.Listener) Iterator(java.util.Iterator) SessionFactory(org.hibernate.SessionFactory) Util(org.infinispan.commons.util.Util) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Contact(org.hibernate.test.cache.infinispan.functional.entities.Contact) TestInfinispanRegionFactory(org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory) TimeUnit(java.util.concurrent.TimeUnit) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) BaseCustomInterceptor(org.infinispan.interceptors.base.BaseCustomInterceptor) Assert.assertNull(org.junit.Assert.assertNull) Customer(org.hibernate.test.cache.infinispan.functional.entities.Customer) FutureUpdate(org.hibernate.cache.infinispan.util.FutureUpdate) Phaser(java.util.concurrent.Phaser) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) VisitableCommand(org.infinispan.commands.VisitableCommand) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) InfinispanMessageLogger(org.hibernate.cache.infinispan.util.InfinispanMessageLogger) Assert.assertEquals(org.junit.Assert.assertEquals) ConcurrentSet(org.jboss.util.collection.ConcurrentSet) HashSet(java.util.HashSet) Set(java.util.Set) Customer(org.hibernate.test.cache.infinispan.functional.entities.Customer) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) HashSet(java.util.HashSet) Contact(org.hibernate.test.cache.infinispan.functional.entities.Contact)

Example 7 with SessionFactory

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

the class SessionRefreshTest method testRefreshAfterExternalChange.

@Test
public void testRefreshAfterExternalChange() throws Exception {
    // First session factory uses a cache
    CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTest.LOCAL);
    localCache = localManager.getCache(Account.class.getName());
    SessionFactory localFactory = sessionFactory();
    // Second session factory doesn't; just needs a transaction manager
    SessionFactory remoteFactory = secondNodeEnvironment().getSessionFactory();
    AccountDAO dao0 = new AccountDAO(useJta, localFactory);
    AccountDAO dao1 = new AccountDAO(useJta, remoteFactory);
    Integer id = new Integer(1);
    dao0.createAccount(dao0.getSmith(), id, new Integer(5), DualNodeTest.LOCAL);
    // Basic sanity check
    Account acct1 = dao1.getAccount(id);
    assertNotNull(acct1);
    assertEquals(DualNodeTest.LOCAL, acct1.getBranch());
    // This dao's session factory isn't caching, so cache won't see this change
    dao1.updateAccountBranch(id, DualNodeTest.REMOTE);
    // dao1's session doesn't touch the cache,
    // so reading from dao0 should show a stale value from the cache
    // (we check to confirm the cache is used)
    Account acct0 = dao0.getAccount(id);
    assertNotNull(acct0);
    assertEquals(DualNodeTest.LOCAL, acct0.getBranch());
    log.debug("Contents when re-reading from local: " + TestingUtil.printCache(localCache));
    // Now call session.refresh and confirm we get the correct value
    acct0 = dao0.getAccountWithRefresh(id);
    assertNotNull(acct0);
    assertEquals(DualNodeTest.REMOTE, acct0.getBranch());
    log.debug("Contents after refreshing in remote: " + TestingUtil.printCache(localCache));
    // Double check with a brand new session, in case the other session
    // for some reason bypassed the 2nd level cache
    AccountDAO dao0A = new AccountDAO(useJta, localFactory);
    Account acct0A = dao0A.getAccount(id);
    assertNotNull(acct0A);
    assertEquals(DualNodeTest.REMOTE, acct0A.getBranch());
    log.debug("Contents after creating a new session: " + TestingUtil.printCache(localCache));
}
Also used : SessionFactory(org.hibernate.SessionFactory) Account(org.hibernate.test.cache.infinispan.functional.entities.Account) CacheContainer(org.infinispan.manager.CacheContainer) Test(org.junit.Test)

Example 8 with SessionFactory

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

the class QueryRegionImplTest method testGetDoesNotBlockPut.

@Test
public void testGetDoesNotBlockPut() throws Exception {
    withQueryRegion((sessionFactory, region) -> {
        withSession(sessionFactory, session -> region.put(session, KEY, VALUE1));
        assertEquals(VALUE1, callWithSession(sessionFactory, session -> region.get(session, KEY)));
        final AdvancedCache cache = ((QueryResultsRegionImpl) region).getCache();
        final CountDownLatch blockerLatch = 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() {
                GetBlocker blocker = new GetBlocker(blockerLatch, KEY);
                try {
                    cache.addListener(blocker);
                    withSession(sessionFactory, session -> region.get(session, KEY));
                } catch (Exception e) {
                    holder.addException(e);
                } finally {
                    cache.removeListener(blocker);
                }
            }
        };
        Thread writer = new Thread() {

            @Override
            public void run() {
                try {
                    writerLatch.await();
                    withSession(sessionFactory, session -> region.put(session, KEY, VALUE2));
                } catch (Exception e) {
                    holder.addException(e);
                } finally {
                    completionLatch.countDown();
                }
            }
        };
        reader.setDaemon(true);
        writer.setDaemon(true);
        boolean unblocked = false;
        try {
            reader.start();
            writer.start();
            assertFalse("Reader is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS));
            // Start the writer
            writerLatch.countDown();
            assertTrue("Writer finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS));
            blockerLatch.countDown();
            unblocked = true;
            if (IsolationLevel.REPEATABLE_READ.equals(cache.getCacheConfiguration().locking().isolationLevel())) {
                assertEquals(VALUE1, callWithSession(sessionFactory, session -> region.get(session, KEY)));
            } else {
                assertEquals(VALUE2, callWithSession(sessionFactory, session -> region.get(session, KEY)));
            }
            holder.checkExceptions();
        } finally {
            if (!unblocked) {
                blockerLatch.countDown();
            }
        }
    });
}
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) QueryResultsRegionImpl(org.hibernate.cache.infinispan.query.QueryResultsRegionImpl) AdvancedCache(org.infinispan.AdvancedCache) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test) AbstractGeneralDataRegionTest(org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTest)

Example 9 with SessionFactory

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

the class QueryRegionImplTest method testPutDuringPut.

@Test
@TestForIssue(jiraKey = "HHH-7898")
public void testPutDuringPut() throws Exception {
    withQueryRegion((sessionFactory, region) -> {
        withSession(sessionFactory, session -> region.put(session, KEY, VALUE1));
        assertEquals(VALUE1, callWithSession(sessionFactory, session -> region.get(session, KEY)));
        final AdvancedCache cache = ((QueryResultsRegionImpl) region).getCache();
        CountDownLatch blockerLatch = new CountDownLatch(1);
        CountDownLatch triggerLatch = new CountDownLatch(1);
        ExceptionHolder holder = new ExceptionHolder();
        Thread blocking = new Thread() {

            @Override
            public void run() {
                PutBlocker blocker = null;
                try {
                    blocker = new PutBlocker(blockerLatch, triggerLatch, KEY);
                    cache.addListener(blocker);
                    withSession(sessionFactory, session -> region.put(session, KEY, VALUE2));
                } catch (Exception e) {
                    holder.addException(e);
                } finally {
                    if (blocker != null) {
                        cache.removeListener(blocker);
                    }
                    if (triggerLatch.getCount() > 0) {
                        triggerLatch.countDown();
                    }
                }
            }
        };
        Thread blocked = new Thread() {

            @Override
            public void run() {
                try {
                    triggerLatch.await();
                    // this should silently fail
                    withSession(sessionFactory, session -> region.put(session, KEY, VALUE3));
                } catch (Exception e) {
                    holder.addException(e);
                }
            }
        };
        blocking.setName("blocking-thread");
        blocking.start();
        blocked.setName("blocked-thread");
        blocked.start();
        blocked.join();
        blockerLatch.countDown();
        blocking.join();
        holder.checkExceptions();
        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) QueryResultsRegionImpl(org.hibernate.cache.infinispan.query.QueryResultsRegionImpl) AdvancedCache(org.infinispan.AdvancedCache) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test) AbstractGeneralDataRegionTest(org.hibernate.test.cache.infinispan.AbstractGeneralDataRegionTest) TestForIssue(org.hibernate.testing.TestForIssue)

Example 10 with SessionFactory

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

the class JBossStandaloneJtaExampleTest method testPersistAndLoadUnderJta.

@Test
public void testPersistAndLoadUnderJta() throws Exception {
    Item item;
    SessionFactory sessionFactory = buildSessionFactory();
    try {
        UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertTrue(session.getTransaction().isActive());
            item = new Item("anItem", "An item owned by someone");
            session.persist(item);
            // IMO the flush should not be necessary, but session.close() does not flush
            // and the item is not persisted.
            session.flush();
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertTrue(session.getTransaction().isActive());
            Item found = (Item) session.load(Item.class, item.getId());
            Statistics stats = session.getSessionFactory().getStatistics();
            log.info(stats.toString());
            assertEquals(item.getDescription(), found.getDescription());
            assertEquals(0, stats.getSecondLevelCacheMissCount());
            assertEquals(1, stats.getSecondLevelCacheHitCount());
            session.delete(found);
            // IMO the flush should not be necessary, but session.close() does not flush
            // and the item is not deleted.
            session.flush();
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertTrue(session.getTransaction().isActive());
            assertNull(session.get(Item.class, item.getId()));
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
    } finally {
        if (sessionFactory != null)
            sessionFactory.close();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) UserTransaction(javax.transaction.UserTransaction) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) Statistics(org.hibernate.stat.Statistics) NameNotFoundException(javax.naming.NameNotFoundException) Session(org.hibernate.Session) Test(org.junit.Test)

Aggregations

SessionFactory (org.hibernate.SessionFactory)106 Test (org.junit.Test)62 Session (org.hibernate.Session)49 Configuration (org.hibernate.cfg.Configuration)34 Transaction (org.hibernate.Transaction)19 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