1.第一種方式:
<beans>
....
<!-- 創建事務管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置註解形式管理事務 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
這種配置完後,我們只需要在我們要加事務的方法前加註解即可,
一般在service層
類上添加@Transactional(readOnly=true)
然後在允許執行的具體的方法前添加@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
2 第二種方式
<beans>
...
<!-- hibernate事務管理器,在service層面上實現事務管理,而且達到平臺無關性 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 事務通知 -->
<tx:advice id="txAdvcie" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="batch*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="get*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>
<tx:method name="load*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>
<tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- aop配置 -->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* *..*Service.*(..))"/>
<aop:advisor advice-ref="txAdvcie" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
事務通知部分,我們已經配置了在以save,update,delete等開頭的方法中執行事務通知(spring默認環繞通知),但是這些方法可能存在於我們的dao層,service層,action層等等。而我們只需要在service層進行事務管理,那麼這就用到了aop【面向切面編程】,上面的<aop:config>只體現了一小部分,將通知的切入點設置到了service層。
個人認爲aop的面向切面,這只是冰山一角,甚至都不算一角,有待更深的挖掘,正在學習中。