Springboot中的数据库事务
对于一些业务网站而言 , 产 品库存的扣减、 交易记录以及账户都必须是要么 同时成功, 要么 同时失败 ,这便是一种事务机制,而在一些特殊的场景下 ,如一个批处理 ,它将处理多个交易 ,但是在一些交易中发生了异常 , 这个时候则不能将所有的交易都回滚。如果所有的交易都回渎,那么那些本能够正常处理的业务也无端地被回滚。 通过 Spring 的数据库事务传播行为,可以很方便地处理这样的场景 。
首先配置数据库信息
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-idle=10
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.initial-size=5
一、JDBC数据库事务
package com.demo.servicee.impl
@Service
public class JdbcServiceImpl implements JdbcService{
@Autowired
private DataSource dataSource=null;
@Override
public int insertUser(String name,String note){
Connection conn=null;
int result=0;
try{
//获取连接
conn=dataSource.getConnection();
//开启事务
conn.setAutoCommit(false);
//设置隔离级别
conn.setTransactionIsolation(TransactionIsolationLevel.RRAD_COMMITED.getLevel());
//执行SQL
PreparedStatement ps=conn.prepareStatement("insert into t_user(user_name,note)values(?,?)");
ps.setString(1,userName);
ps,setString(2,note);
result=ps.executeUpdate();
//提交事务
conn.commit();
}catch(Exception e){
//回滚事务
if(conn !=null){
try{
conn.rollback();
}catch(SqlException e1)
e1.printStackTrace();
}
}
e.printStackTrace();
}finally{
try{
if(conn !=null && !conn.isClosed()){
conn.close()
}
}catch(SQLException e){
e.printStackTrace();
}
}
return result;
}
}
使用JDBC需要使用大量的try...catch...finally...语句,和关于连接的获取关闭,事务的提交和回滚。使用Hibernate、myBatis可以减少try...catch...finally的使用,但是依旧不能减少开闭数据库连接和事务控制的代码。而AOP可以解决这样的问题。
二、Spring 声明式事务的使用
Spring AOP 会把我们的代码织入到约定的流程中,同样,同样执行的SQL的代码也可以织入的哦Spring 约定的数据库事务的流程中。首先要掌握这个约定
1.Spring 声明式数据库事务约定
对于事务需要通过标注告诉Spring在什么地方启用数据库事务功能,对于声明式数据库,是使用@Transactional进行标注的。
@Transactional 这个注解可以标注类和方法上,当它标注在类上时,代表这个类所有公共(public)非静态的方法东将启用事务功能。在@Transactonal 中还可以进行事务的隔离级别和传播行为,异常类型的配置。这些配置,是在Sprng IoC容器在加载时就会将这些配置信息解析出来,然后帮这些喜喜存储到事务定义器(TransactonDefinition接口实现的类)里,并且记录了那些类或者方法需要启动事务的功能,采取什么策略去执行事务。在这个过程中我们所需要做的就是给需要事务的类和方法标注@Transactional并配置属性
spring的事务处理机制
Sprin