1.導入所需jar包(Spring3.0之后不再一起發布依賴包,要自行下載)
2.在applicationContext.xml下配置事務管理器Bean
<!-- 配置事務管理器, --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
3.在配置文件的頭部引入<tx>和<aop>命名空間
<tx>命名空間:
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
<aop>命名空間:
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
完整的頭部信息:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd ">
4.配置事務屬性
<tx:advice id="daoAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delect*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice>
transaction-manager="transactionManager" 引入Spring事務管理類
name="delect*" 要執行(delect開頭)的方法名,propagation="REQUIRED"有transaction狀態下執行。如果當前沒有transaction,就創建新的transaction。
read-only="true" 設置是否只讀。
5.AOP的配置
<aop:config> <aop:pointcut expression="execution(* dao.*.*(..))" id="daoMethod"/> <aop:advisor advice-ref="daoAdvice" pointcut-ref="daoMethod"/> </aop:config>
expression="execution(* dao.*.*(..))" 第一個*代表所有的返回值類型,dao代表包名,第二個*帶表所有的類,第三個*代表所有的方法,(..)代表方法的參數。
6.在需要事務的方法里就不用寫事務的開始、事務的提交和關閉session。
package dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;import entity.News; @Repository @Scope("prototype") public class NewsDaoImpl implements NewsDaoIntf{ @Autowired @Qualifier("sessionFactory") private SessionFactory sf; private List<News> list=new ArrayList<News>(); @Override public List<News> getAllNews() { Session session=sf.getCurrentSession(); session.getTransaction().begin(); Query query=session.createQuery("from News"); list=query.getResultList(); session.getTransaction().commit();
return list; } }