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 {@AutowiredUserMapper userMapper;public List<User> selectAllUser() {// TODO Auto-generated method stubreturn userMapper.selectAllUser();} /*?@Overridepublic List<User> selectAllUser(Page page) {// TODO Auto-generated method stubreturn userMapper.selectAllUser(page);}@Overridepublic int total() {// TODO Auto-generated method stubreturn userMapper.total();}*/@Overridepublic User selectUser(Integer id) {// TODO Auto-generated method stubreturn userMapper.selectUser(id);}@Overridepublic void updateUser(User user) {// TODO Auto-generated method stubuserMapper.updateUser(user);}@Overridepublic void deleteUser(int id) {// TODO Auto-generated method stubuserMapper.deleteUser(id);}@Overridepublic void addUser(User user) {// TODO Auto-generated method stubuserMapper.addUser(user);}@Override/*@Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="Exception")*/public void addTwo() {// TODO Auto-generated method stubUser user1 = new User();user1.setName("張三");user1.setAge(22);userMapper.addUser(user1);//用戶2故意設置名字長度過長User user2 = new User();user2.setName("嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿");user2.setAge(25);userMapper.addUser(user2);}@Overridepublic void deleteAll() {// TODO Auto-generated method stubList<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();//執行插入兩個useruserService.addTwo();}/*? @Testpublic void testTotal() {int total = userMapper.total();System.out.println(total);}@Testpublic 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.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://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 stubUser 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();//執行插入兩個useruserService.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.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://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
總結
以上是生活随笔為你收集整理的SSM中进行注解式和XML配置式事务管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SSM中实现CRUD并配置输出sql语句
- 下一篇: The server time zone