- 事务———把一些操作放在一起处理,要么全部成功,要么全部失败。
在这里我们介绍一下ssh整合的时候,事务的使用和管理。
这是声明事务管理,所以不需要写代码,只需要在 applicationContext.xml 文件中配置一下就行了。
第一步:声明命名空间
xmlns:aop=”http://www.springframework.org/schema/aop”
xmlns:tx=”http://www.springframework.org/schema/tx”
xsi:schemaLocation=“http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd”
切记,这些 命名空间是有顺序的呦。
第二步:声明一个事务管理器,并把它命名为 id=“”,class=“”是所在类的路径
<bean id = "HibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
第三步:声明事务通知,id是自己命名的名字,transaction-manager声明一个为HibernateTransactionManager的代理类。tx:attributes是事务的范围限定,tx:method name=”xx*” propagation=”REQUIRED,以xx开始的方法都要放在事务里面。tx:method name=”login*” propagation=”SUPPORTS read-only=”true” 表示有事务了放在事务里边,并标记为只读,没事务就不在管理。
<!-- 事务通知 -->
<tx:advice id="txAdvice" transaction-manager="HibernateTransactionManager">
<tx:attributes>
<!-- 必须放在事务里边的 -->
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<!-- 有事务放在事务里,并标记为只读,没事务就不放在事务里 -->
<tx:method name="login*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
- 下面附上完整分代码
<!-- 事务管理器 -->
<bean id = "HibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务通知 -->
<tx:advice id="txAdvice" transaction-manager="HibernateTransactionManager">
<tx:attributes>
<!-- 必须放在事务里边的 -->
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<tx:method name="" propagation="REQUIRED"/>
<!-- 有事务放在事务里,并标记为只读,没事务就不放在事务里 -->
<tx:method name="login*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="bizAop" expression="execution(* com.jfl.biz.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="bizAop" />
</aop:config>