Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda