Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
How I can use transactions in TestNG @BeforeClass?

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!