spring中如何做事务?(标准做法---集成hibernate)
spring中如何做事务?(标准做法---集成hibernate)
配置如下:
<bean id="sessionFactory" ><property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property></bean> <bean id="transactionManager" > <property name="sessionFactory" ref="sessionFactory" /></bean> <tx:advice id="txAdivce" transaction-manager="transactionManager" > <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="allDao" expression="execution(* com.cs.dao.*.*(..))" /> <aop:advisor advice-ref="txAdivce" pointcut-ref="allDao" /> </aop:config>
<bean id="teamDao" ref="sessionFactory" /> //必须要配上,因为继承自hibernateDaoSupport </bean>解析:
<bean id="sessionFactory" ><property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property></bean>
<bean id="transactionManager" > <property name="sessionFactory" ref="sessionFactory" /></bean>
<tx:advice id="txAdivce" transaction-manager="transactionManager" > <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice>
<aop:config> <aop:pointcut id="allDao" expression="execution(* com.cs.dao.*.*(..))" /> <aop:advisor advice-ref="txAdivce" pointcut-ref="allDao" /> </aop:config>
public class PersonDaoImpl extends HibernateDaoSupport implements PersonDao { private TeamDao teamDao ; public void addPerson(Person p) { //在这里不用再去考虑事务的开启和关闭以及传播(这就是spring中作事务的优点所在) this.getHibernateTemplate().saveOrUpdate(p) ; teamDao.addTeam(p.getTeam()) ;}public TeamDao getTeamDao() {return teamDao;}public void setTeamDao(TeamDao teamDao) {this.teamDao = teamDao;}}