1. 程式人生 > >SSM中進行註解式和XML配置式事務管理

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