[英]Spring/Hibernate/TestNG - manual session and transaction setup
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:我正在尝试为使用普通 Hibernate API 的 DAO 类创建一个测试用例(没有 Spring 之类的东西,例如 HibernateTemplate,HibernateDaoSupport),就像这样:
sessionFactory.getCurrentSession().save(obj);
I have the appropriate sessionFactory and transactionManager definition in spring context as shown in the spring docs.我在 spring 上下文中有适当的 sessionFactory 和 transactionManager 定义,如 spring 文档中所示。
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 AbstractTransactionalTestNGSpringContextTests.因此,这与默认的 Spring 单元测试支持每个测试方法调用的事务概念不同,因此我无法扩展 AbstractTransactionalTestNGSpringContextTests。
I need a way to start a transaction and somehow feed it in session factory.我需要一种方法来启动交易并以某种方式将其提供给 session 工厂。 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 .如果不想使用
HibernateTemplate
,可以直接使用transactionManager
,如10.6.2 使用 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) @Transactional(只读 = 假,传播 = Propagation.REQUIRED)
annotate the test method using above使用上面的注释测试方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.