2015-04-27 38 views
1

我爲我的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事務管理。

回答

1

如果您使用Hibernate讓您的DAO類擴展HibernateDaoSupport。現在您可以從getHibernateTemplate()方法獲取會話。這樣,你可以通過有管理的會話彈簧休眠

你可以試試這個 - 從appcontext.xml

<tx:annotation-driven transaction-manager="transactionManager" /> 

-

appContext.xml

<tx:advice id="txAdvice" transaction-manager="transactionManager"> 
     <tx:attributes> 
     <tx:method name="submit*" propagation="REQUIRED" read-only="false" rollback-for="Exception"/> 
</tx:attributes> 
    </tx:advice> 
    <aop:config> 
     <aop:pointcut id="appControllerTransactionPointCuts" 
      expression="execution(* com.test.customer.bo.Custom.*(..))" /> 
<aop:advisor advice-ref="txAdvice" pointcut-ref="appControllerTransactionPointCuts" /> 
    </aop:config> 

刪除

現在AOP應該管理交易。

事務如何工作 - 假設您在多個DAO方法中持久化對象,並且希望它們都發生在一個事務中,則必須在調用DAO方法的服務層方法上應用事務。對於e,在我的情況下,服務層是com.test.customer.bo.Custom。*

如果你不這樣做,那麼你的每個DAO方法將在一個單獨的事務中執行並且將被持久化如果沒有發生異常,則將其發送到數據庫如果在DAO層的method2()中發生異常,它將不會回滾方法1(),因爲它已經提交。

+0

同時在你的spring應用上下文中添加tx:annotationdriven,這樣spring將管理事務 – Waqar

+0

我已經試過了。但交易不是回滾。 – Daya

+0

您是否添加了,因爲您也在使用AOP – Waqar