我正在为我的 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() 持久化的数据不是 rollback。
请让我知道,如何在不丢失 Spring 事务管理的情况下基于线程获取单个会话(如果我使用自己的 HibernateFactory,我会失去 Spring 的事务管理)。