开发者

Spring/Hibernate/TestNG - manual session and transaction setup

开发者 https://www.devze.com 2023-03-16 01:29 出处:网络
I am trying to create a testcase for my DAO classes that use plain Hibernate API (no Spring stuff like HibernateTemplate,HibernateDaoSupport), just like this:

I am trying to create a testcase for my DAO classes that use plain Hibernate API (no Spring stuff like HibernateTemplate,HibernateDaoSupport), just like this:

sessionFactory.getCurrentSession().save(obj);

I have the appropriate sessionFactory and transactionManager definition in spring context as shown in the spring docs.

What I want is to open a transaction in my start up code and rollback at the end.

So this is different from the default Spring unit testing supporting concept of transaction for every test method call and so I could not extend AbstractTransactionalTestNGSpringConte开发者_开发技巧xtTests.

I need a way to start a transaction and somehow feed it in session factory. I feel this should be extremely easy but could not achieve after lot of reading and experiments.

Any help would be greatly appreciated.


If you don't want to use HibernateTemplate, you can use transactionManager directly as described in 10.6.2 Using the PlatformTransactionManager.


try {
  Session session = factory.openSession();
  Transaction tx = session.beginTransaction();
  ...
  tx.commit();
  session.close();
} catch (SomeException e) {
  tx.rollback();
  ...
}


@Transactional(readOnly = false, propagation = Propagation.REQUIRED)

annotate the test method using above

0

精彩评论

暂无评论...
验证码 换一张
取 消