SSM中进行注解式和XML配置式事务管理

场景

前面实现SSM简单整合以及CRUD参照:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/85161018

SSM中配置事务管理所需jar包:

https://download.csdn.net/download/badao_liumang_qizhi/10867618

Mysql的表必须是INNODB的引擎才支持

实现

导入jar包

将事务所需jar包放在项目lib目录下

修改service

给接口添加deleteAll方法以及addTwo()方法

package com.badao.service;

import java.util.List;

import com.badao.pojo.User;
import com.badao.util.Page;

public interface UserService {
 List<User> selectAllUser();

 User selectUser(Integer id);

 void updateUser(User user);

 void deleteUser(int id);

 void addUser(User user);
 
 void addTwo();
 
 void deleteAll();
 
 //List<User> selectAllUser(Page page);
 //int total();

}

修改serviceImpl

先删除所有User,然后再插入两个User,其中第二个User故意设置名字过长。

package com.badao.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.badao.mapper.UserMapper;
import com.badao.pojo.User;
import com.badao.service.UserService;
import com.badao.util.Page;
@Service
public class UserServiceImpl implements UserService {

 @Autowired
 UserMapper userMapper;
 public List<User> selectAllUser() {
  // TODO Auto-generated method stub
  return userMapper.selectAllUser();
 }
/* @Override
 public List<User> selectAllUser(Page page) {
  // TODO Auto-generated method stub
  return userMapper.selectAllUser(page);
 }
 @Override
 public int total() {
  // TODO Auto-generated method stub
  return userMapper.total();
 }*/
 @Override
 public User selectUser(Integer id) {
  // TODO Auto-generated method stub
  return userMapper.selectUser(id);
 }
 @Override
 public void updateUser(User user) {
  // TODO Auto-generated method stub
      userMapper.updateUser(user);
 }
 @Override
 public void deleteUser(int id) {
  // TODO Auto-generated method stub
  userMapper.deleteUser(id);
 }
 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  userMapper.addUser(user);
 }
 
 
 @Override
 /*@Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="Exception")*/
 public void addTwo() {
  // TODO Auto-generated method stub
  User user1 = new User();
  user1.setName("张三");
  user1.setAge(22);
  userMapper.addUser(user1);
  //用户2故意设置名字长度过长
  User user2 = new User();
  user2.setName("嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿");
  user2.setAge(25);
  userMapper.addUser(user2);
 }
 @Override
 public void deleteAll() {
  // TODO Auto-generated method stub
   List<User> userList = selectAllUser();
   for (User user : userList) {
   userMapper.deleteUser(user.getId());
  }
 }

}

编写测试类

package com.badao.test;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import com.badao.mapper.UserMapper;
import com.badao.pojo.User;
import com.badao.service.UserService;
import com.badao.util.Page;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;//使用junit4时报错导这个包
@RunWith(SpringJUnit4ClassRunner.class)//使用junit4进行测试
@ContextConfiguration("classpath:applicationContext.xml")//加载配置文件
public class InsertTest {
 @Autowired//自动注入
 private UserMapper userMapper;
 @Autowired//自动注入
 private UserService userService;
  @Test//标明是测试方法
  @Rollback(false)  //标明使用完此方法后事务不回滚,true时为回滚
  public void testAdd() {
         for (int i = 0; i < 100; i++) {
          User user = new User();
          user.setName("user"+i);
             userMapper.addUser(user);
         }
 
     }
  @Test//标明是测试方法
  public void testAddTwo() {
   //删除全部没用数据
   userService.deleteAll();
   //执行插入两个user
   userService.addTwo();
  }
     
   /*  @Test
     public void testTotal() {
         int total = userMapper.total();
         System.out.println(total);
     }
 
     @Test
     public void testList() {
         Page p = new Page();
         p.setStart(2);
         p.setCount(3);
         List<User> cs=userMapper.selectAllUser(p);
         for (User c : cs) {
             System.out.println(c.getName());
         }
     }*/
}

配置applicationContext.xml

进行事务配置,添加事务管理器和事务注解扫描器

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
 </bean>

完整代码

<?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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
 


   <context:annotation-config />
   <context:component-scan base-package="com.badao.service" />

<!--  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
   <property name="driverClassName"> 
       <value>com.mysql.jdbc.Driver</value> 
   </property> 
   <property name="url"> 
       <value>jdbc:mysql://localhost:3306/ssmtest?characterEncoding=UTF-8</value> 
   </property> 
   <property name="username"> 
       <value>root</value> 
   </property> 
   <property name="password"> 
       <value>523627</value> 
   </property>   
 </bean> -->
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name= "url"value="jdbc:mysql://localhost:3306/ssmtest?characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="523627" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
 
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="3" />
        <property name="minIdle" value="3" />
        <property name="maxActive" value="20" />
 
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
 
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
 
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
 
        <property name="validationQuery" value="SELECT 1" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
 
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
    </bean>
 
 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="typeAliasesPackage" value="com.badao.pojo" />
  <property name="dataSource" ref="dataSource"/>
  <property name="mapperLocations" value="classpath:com/badao/mapper/*.xml"/>
  <property name="plugins">
            <array>
              <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                  <!--使用下面的方式配置参数,一行配置一个 -->
                  <value>
                  </value>
                </property>
              </bean>
            </array>
          </property>  
 </bean>

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.badao.mapper"/>
 </bean>
 
 <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
</beans>

使用注解方式

为serviceImpl里的addTwo()方法加上事务注解

@Override
 @Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="Exception")
 public void addTwo() {
  // TODO Auto-generated method stub
  User user1 = new User();
  user1.setName("张三");
  user1.setAge(22);
  userMapper.addUser(user1);
  //用户2故意设置名字长度过长
  User user2 = new User();
  user2.setName("嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿");
  user2.setAge(25);
  userMapper.addUser(user2);
 }

运行测试

运行测试类中的testAddTwo()方法

@Test//标明是测试方法
  public void testAddTwo() {
   //删除全部没用数据
   userService.deleteAll();
   //执行插入两个user
   userService.addTwo();
  }

先将数据库中的数据删除干净,然后再执行插入两个User,

因为第二个user的名字过长,所以报异常,导致事务回滚,所以第一个user的插入会回滚,可以看到数据库中是一条数据都没有。

使用XML配置事务

注释掉上面注解的部分,包括serviceImpl中的方法上的注解,修改applicationContext.xml

<?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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
 


   <context:annotation-config />
   <context:component-scan base-package="com.badao.service" />

<!--  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
   <property name="driverClassName"> 
       <value>com.mysql.jdbc.Driver</value> 
   </property> 
   <property name="url"> 
       <value>jdbc:mysql://localhost:3306/ssmtest?characterEncoding=UTF-8</value> 
   </property> 
   <property name="username"> 
       <value>root</value> 
   </property> 
   <property name="password"> 
       <value>523627</value> 
   </property>   
 </bean> -->
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name= "url"value="jdbc:mysql://localhost:3306/ssmtest?characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="523627" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
 
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="3" />
        <property name="minIdle" value="3" />
        <property name="maxActive" value="20" />
 
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
 
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
 
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
 
        <property name="validationQuery" value="SELECT 1" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
 
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
    </bean>
 
 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="typeAliasesPackage" value="com.badao.pojo" />
  <property name="dataSource" ref="dataSource"/>
  <property name="mapperLocations" value="classpath:com/badao/mapper/*.xml"/>
  <property name="plugins">
            <array>
              <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                  <!--使用下面的方式配置参数,一行配置一个 -->
                  <value>
                  </value>
                </property>
              </bean>
            </array>
          </property>  
 </bean>

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.badao.mapper"/>
 </bean>
 
 <!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
    <tx:advice id="txadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="del*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="edit*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="list*" propagation="REQUIRED" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>
       
    <aop:config>
        <aop:pointcut id="serviceMethod" expression="execution(* com.badao.service.*.*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txadvice"/>
    </aop:config>     



</beans>

再次运行测试类

再执行上面的测试一样的效果。

源码下载

https://download.csdn.net/download/badao_liumang_qizhi/10867762

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值