【发布时间】:2015-04-27 17:38:51
【问题描述】:
我正在为我的 Web 应用程序使用 Struts2.3 + Spring 3.2.6 + Hibernate 3.X。
我正在使用注释来管理事务。 我的 DAO 类如下。
@Transactional(readOnly = true, rollbackFor={Exception.class})
public class CustomerDAOImpl extends HibernateDaoSupport implements CustomerDAO{
//adds the customer
@Transactional(propagation=Propagation.REQUIRED, rollbackFor = {Exception.class})
public void addCustomer(Customer customer){
Session session = getSession();
System.out.println("M1() Hash Code: --->"+session.hashCode()+ " Thread id: "+Thread.currentThread().getId());
//session.save(customer);
}
//return all the customers in list
// @Transactional(propagation=Propagation.REQUIRED, rollbackFor = {Exception.class})
@Transactional(readOnly = true)
public List<Customer> listCustomer(){
Session session = getSession();
System.out.println("M2() Hash Code: --->"+session.hashCode()+ " Thread id: "+Thread.currentThread().getId());
return null; //logic to get the list based on condition
}
这些方法将从服务层调用,如下所示;
customerDAO.addCustomer(customer);
customerDAO.listCustomer();
执行上述代码时,我得到同一线程的不同会话。
输出:
M1() Hash Code: --->5026724 Thread id: 21
M2() Hash Code: --->8899550 Thread id: 21
因此,如果在 method2() 中出现任何异常,则使用 method1() 持久化的数据不会回滚。
请告诉我,如何在不丢失 Spring 事务管理的情况下获得基于线程的单个会话(如果我使用自己的 HibernateFactory,我会失去 Spring 的事务管理)。
【问题讨论】:
标签: java spring hibernate spring-transactions spring-orm