I use TestNG + Spring + hibernate. When I use transaction in @BeforeClass, I get:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
Code example:
@Transactional(transactionManager = "transactionManager")
@Rollback
@ContextConfiguration(locations = "/WEB-INF/testing/applicationTestContext.xml")
@TestExecutionListeners(listeners = {
ServletTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class,
WithSecurityContextTestExecutionListener.class
})
public abstract class ExampleOfTest extends AbstractTestNGSpringContextTests{
@Autowired
private SessionFactory sessionFactory;
@BeforeClass
public void setUpClass() {
sessionFactory.getCurrentSession().beginTransaction(); // get HibernateException
sessionFactory.getCurrentSession().getTransaction().commit();
}
....
}
How I can use transaction in @BeforeClass? I want to use this for one-time data entry used in all class tests.
Problem would be @EnableTransactionManagement should be in your spring context
or
Try something like
// BMT idiom with getCurrentSession()
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work on Session bound to transaction
sessionFactory.getCurrentSession().persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
getCurrentSession is like restricted, it should run in a active transaction.
I think this may help.