1.要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager
对象:
<!--配置声明式事务-->
<bean id="transationManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transationManager">
<tx:attributes>
<!--给那些方法配置事务-->
<!--propagation 配置事务的传播性-->
<tx:method name="addUser" propagation="REQUIRED"/>
<tx:method name="delUser" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务的切入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.zuo.dao.UserMapperImpl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>
事务的管理有两种
第一种:交由容器管理事务
(1)配置事务
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> UserList() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
User addUser = new User(5, "xiaoKUN", "123456");
mapper.addUser(addUser);
mapper.delUser(5);
return mapper.UserList();
}
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int delUser(int id) {
return getSqlSession().getMapper(UserMapper.class).delUser(id);
}
}
(2)在spring-dao.xml中配置声明式事务
<!--配置声明式事务-->
<bean id="transationManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transationManager">
<tx:attributes>
<!--给那些方法配置事务-->
<!--propagation 配置事务的传播性-->
<tx:method name="addUser" propagation="REQUIRED"/>
<tx:method name="delUser" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务的切入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.zuo.dao.UserMapperImpl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>
(3)测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper mapper = context.getBean("userMapper2", UserMapper.class);
List<User> userList = mapper.UserList();
for (User user : userList) {
System.out.println(user);
}
}
}
第二种:编程式的事务管理
定义显式的捕获异常和业务的回滚操作
标签:mapper,事务,14,addUser,spring,UserMapper,public,User,class From: https://www.cnblogs.com/zuok/p/17060905.html