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;
}
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));
}
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();
}
}
});
}
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)));
});
}
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();
}
}
Aggregations