@SuppressWarnings("rawtypes")
public void testJtaSessionSynchronizationWithSpringTransactionLaterOn() throws Exception {
UserTransaction ut = mock(UserTransaction.class);
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
given(tm.getTransaction()).willReturn(transaction);
final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
final Session session = mock(Session.class);
given(sf.openSession()).willReturn(session);
given(sf.getTransactionManager()).willReturn(tm);
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
final HibernateTemplate ht = new HibernateTemplate(sf);
ht.setExposeNativeSession(true);
for (int i = 0; i < 2; i++) {
ht.executeFind(new HibernateCallback() {
@Override
public Object doInHibernate(org.hibernate.Session sess) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertEquals(session, sess);
return null;
}
});
}
TransactionTemplate tt = new TransactionTemplate(new JtaTransactionManager(ut));
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
for (int i = 2; i < 5; i++) {
ht.executeFind(new HibernateCallback() {
@Override
public Object doInHibernate(org.hibernate.Session sess) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertEquals(session, sess);
return null;
}
});
}
}
});
Synchronization synchronization = transaction.getSynchronization();
assertTrue("JTA synchronization registered", synchronization != null);
synchronization.beforeCompletion();
synchronization.afterCompletion(Status.STATUS_COMMITTED);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));