通过案例掌握Spring 管理事务的步骤及配置
案例描述
通过完成生成订单业务,掌握事务处理。
需要d_order表和d_item表
订单生成时的业务逻辑:向d_order插入1条数据的同时,向t_item中插入若干条数据
这就是一个独立的事务,
我们乊前做的是单表操作,使用默认事务即可,但是涉及到稍复杂的多表操作时,我们就需要
做事务处理。
如果我们按乊前的方式,在Action中调用DAO,是没有办法将两个DAO操作封装为一个
事务的。 为此,我们需要再分层,提出Service,在service中迚行事务控制。
参考代码
20) 使用工程spring4<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///test"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> <property name="maxActive" value="10"></property> <property name="initialSize" value="2"></property> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"></property> <property name="mappingResources"> <list> <value>tarena/mapping/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <bean id="userDao" class="tarena.dao.impl.HibernateUserDAOImpl"> <property name="sessionFactory" ref="mySessionFactory"> </property> </bean> <bean id="userService" class="tarena.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <!-- 声明式事务控制 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory"> </property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="within(tarena.service..*)" id="servicePointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/> </aop:config> </beans>