我爲我的web應用程序使用Struts2.3 + Spring 3.2.6 + Hibernate 3.X。Spring HibernateDaoSupport創建多個會話
我正在使用註釋來管理事務。 我的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
由於這個原因,如果任何異常來在方法2(),它是使用方法1()不回滾持久的數據。
請讓我知道,如何獲得基於線程的單一會話(如果我爲我自己的HibernateFactory去掉了Spring的事務管理)而不支持spring事務管理。
同時在你的spring應用上下文中添加tx:annotationdriven,這樣spring將管理事務 – Waqar
我已經試過了。但交易不是回滾。 – Daya
您是否添加了 或 ,因爲您也在使用AOP –
Waqar