SSM - 事务回滚(注解方式实现)
发布时间:2018-12-09 18:44,
浏览次数:913
, 标签:
SSM
文章目录
* MYSQL 表的类型必须是 INNODB 才支持事务。
* 核心代码
* 在配置文件注册事务管理器和开启注解驱动
* 在 Service 实现类编写方法并使用注解
* 完整 Demo
<>MYSQL 表的类型必须是 INNODB 才支持事务。
MYSQL 表的类型必须是 INNODB 才支持事务。
在 Mysql 中,只有当表的类型是 INNODB 的时候,才支持事务,所以需要把表的类型设置为 INNODB, 否则无法观察到事务。如果当前的
MYSQL 服务器本身不支持 INNODB, 需要开启 MYSQL INNODB。
查看表的类型的 SQL: show table status from daily;
修改表的类型为 INNODB 的 SQL: alter table note ENGINE = innodb;
利用 navicat 查看表类型
MySQL 表类型 MyISAM/InnoDB 的区别
MyISAM:这个是默认类型,ISAM 是 Indexed Sequential Access Method (有索引的顺序访问方法)
的缩写,它是存储记录和文件的标准方法。不是事务安全的,也不支持外键。如果执行大量的 SELECT,MyISAM 是更好的选择。
InnoDB:这种类型是事务安全的,还支持外键。InnoDB 表格速度很快。如果你的数据执行大量的 INSERT 或
UPDATE,出于性能方面的考虑,应该使用 InnoDB 表,对于支持事物的 InnoDB 类型的表,影响速度的主要原因是 AUTOCOMMIT
默认设置是打开的,而且程序没有显式调用 BEGIN 开始事务,导致每插入一条都自动 Commit,严重影响了速度。可以在执行 SQL 前调用 BEGIN,多条
SQL 形成一个事物(即使 AUTOCOMMIT 打开也可以),将大大提高性能。
<>核心代码
<>在配置文件注册事务管理器和开启注解驱动
applicationContext.xml
"transactionManager"/>
"org.springframework.jdbc.datasource.DataSourceTransactionManager">
name="dataSource" ref="dataSource"/>
<>在 Service 实现类编写方法并使用注解
此处,数据库中限制了 Student 表的 name 字段长度,如超过会出现异常。因为 add(s2) 抛异常,回滚后,会导致 s1 也无法插入。
StudentServiceImpl.java
@Override @Transactional(propagation= Propagation.REQUIRED,rollbackForClassName
="Exception") public void addTwoStudentThrowsException(Student s1,Student s2) {
studentDao.insertStudent(s1); studentDao.insertStudent(s2); }
测试
@Test public void test2() { Student s1 = new Student("张三",23); Student s2 = new
Student("字段长度超过限制,字段长度超过限制",25); studentService.addTwoStudentThrowsException(s1,
s2); }
异常信息
org.springframework.dao.DataIntegrityViolationException: ### Error querying
database. Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too
long for column 'name' at row 1
也可以自定义异常:
SqlRollbackException.java
public class SqlRollbackException extends RuntimeException { public
SqlRollbackException() { super(); } public SqlRollbackException(String message)
{ super(message); } }
StudentServiceImpl.java
@Override @Transactional public void addTwoStudentThrowsCustomException(
Student s1,Student s2) { try { studentDao.insertStudent(s2); studentDao.
insertStudent(s1); }catch (Exception e){ throw new SqlRollbackException("异常,回滚")
; } }
测试
@Test public void test3() { Student s1 = new Student("张三",23); Student s2 = new
Student("字段长度超过限制,字段长度超过限制",25); studentService.
addTwoStudentThrowsCustomException(s1,s2); }
异常信息
top.qingrang.exception.SqlRollbackException: 异常,回滚
效果同上,两条记录都无法插入数据库。
<>完整 Demo
https://github.com/SSGamble/TransactionDemo