We want a simple unit test to run multiple threads - the idea is that the main thread commits the save to the database and then expects the secondary thread to pick it up.
We find that the transaction must be committed to the second thread in order to be able to query the database and find the item. Otherwise, it will not exist.
We are trying to accomplish this using the H2 database, Hibernate for access control, and unit test extends AbstractTransactionalJUnit4SpringContextTests .
When we try to commit() existing transaction:
... // Create and save our model object sessionFactory.getCurrentSession().getTransaction().commit(); sessionFactory.getCurrentSession().beginTransaction(); ... // Create and start second Thread, query, etc.
We get the error:
org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:484) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:521)`
But when we try to extend only AbstractJUnit4SpringContextTests and use @Transactional annotations:
@TransactionConfiguration(defaultRollback=false, transactionManager="transactionManager") @Transactional() public class DatabaseIntegrityTest extends AbstractJUnit4SpringContextTests {
With the same commit code on top, we get:
org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1041)
During our first call to getCurrentSession() .
Is there a way to halfway through the JUnit Transactional Spring test?
Further, when we try to create our own nested transaction using AbstractTransactionalJUnit4SpringContextTests , we get:
org.hibernate.TransactionException: nested transactions not supported at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:152) at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396)
Edit w / Answer:
Thanks axtavt , I was able to fix everything:
1) Extension AbstractJUnit4SpringContextTests
2) Using @Autowired for PlatformTransactionManager :
@Autowired protected PlatformTransactionManager transactionManager;
3) Entering my transaction code inside:
TransactionStatus status = transactionManager.getTransaction(null); ...