事务是什么?
事务的特性
并发事务的问题
事务的隔离级别
public interface PlatformTransactionManager extends TransactionManager {
TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
事务传播机制,也就是在事务在多个方法的调用中是如何传递的;如:两个service的方法都是事务操作,一个事务方法调用另一个事务方法如何进行处理?
public interface TransactionDefinition {
// 事务的传播机制
// 如果调用方有事务则使用调用方的事务,如果不存在事务则创建一个事务
int PROPAGATION_REQUIRED = 0;
// 跟随调用方,如果调用方有 那就用,调用方没有那就不用
int PROPAGATION_SUPPORTS = 1;
// 调用方的方法必须运行在一个事务中,不存在事务则抛出异常
int PROPAGATION_MANDATORY = 2;
// 不管调用方是否有事务执行,自己都要起一个新事务。把原先的事务挂起,这个只在jta的事务管理器中起作用(事务是不支持嵌套的)
int PROPAGATION_REQUIRES_NEW = 3;
// 即使调用方有事务,我也要在非事务中执行,把原先的事务挂起
int PROPAGATION_NOT_SUPPORTED = 4;
// 绝不在事务里面执行
int PROPAGATION_NEVER = 5;
// 嵌套事务(实际是不支持的,是利用存盘点来实现,把调用方之前执行的存盘点,然后类似于再开启一个事务执行,执行完毕后恢复存盘点,继续执行。JDBC3.0以上支持)
int PROPAGATION_NESTED = 6;
// 以下定义的是事务的隔离机制
// 根据数据库的默认的隔离机制而定
int ISOLATION_DEFAULT = -1;
// 读未提交
int ISOLATION_READ_UNCOMMITTED = 1; // same as java.sql.Connection.TRANSACTION_READ_UNCOMMITTED;
// 读已提交
int ISOLATION_READ_COMMITTED = 2; // same as java.sql.Connection.TRANSACTION_READ_COMMITTED;
// 可重复读
int ISOLATION_REPEATABLE_READ = 4; // same as java.sql.Connection.TRANSACTION_REPEATABLE_READ;
// 串行化
int ISOLATION_SERIALIZABLE = 8; // same as java.sql.Connection.TRANSACTION_SERIALIZABLE;
// 默认超时时间,以数据库设定为准
int TIMEOUT_DEFAULT = -1;
// 获取事务的传播属性
default int getPropagationBehavior() {
return PROPAGATION_REQUIRED;
}
// 获取事务的隔离级别
default int getIsolationLevel() {
return ISOLATION_DEFAULT;
}
// 获取事务超时时间
default int getTimeout() {
return TIMEOUT_DEFAULT;
}
// 事务是否只读。
default boolean isReadOnly() {
return false;
}
// 获取事务的名称
@Nullable
default String getName() {
return null;
}
// 返回一个默认事务定义
static TransactionDefinition withDefaults() {
return StaticTransactionDefinition.INSTANCE;
}
}
// Savepoiont就是在Nested这种传播机制中提供保存点机制来实现嵌套事务,出错的时候可以选择恢复到保存点
public interface TransactionStatus extends TransactionExecution, SavepointManager, Flushable {
// 是否有保存点
boolean hasSavepoint();
@Override
void flush();
}
public interface TransactionExecution {
// 是否是一个新事务
boolean isNewTransaction();
// 设置事务回滚
void setRollbackOnly();
// 事务是否回滚
boolean isRollbackOnly();
// 获取事务是否完成
boolean isCompleted();
}
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDAO accountDAO;
@Autowired
PlatformTransactionManager transactionManager;
/**
* 声明式事务
* propagation = Propagation.REQUIRED (默认值就是REQUIRED) 如果调用方有事务就直接使用调用方的事务,如果没有就新建一个事务
* transactionManager = "transactionManager" 也是默认值
* isolation= Isolation.DEFAULT 隔离级别
* 还有timeout等参数 可自行查看Transactional的源码 里面都有说明
* @param sourceAccountId 源账户
* @param targetAccountId 目标账户
* @param amount 金额
* @return 操作结果信息
*/
@Override
@Transactional(transactionManager = "transactionManager",propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation= Isolation.DEFAULT)
public String transferAnnotation(Long sourceAccountId, Long targetAccountId, BigDecimal amount) {
AccountDO sourceAccountDO = accountDAO.selectByPrimaryKey(sourceAccountId);
AccountDO targetAccountDO = accountDAO.selectByPrimaryKey(targetAccountId);
if (null == sourceAccountDO || null == targetAccountDO) {
return "转入或者转出账户不存在";
}
if (sourceAccountDO.getBalance().compareTo(amount) < 0) {
return "转出账户余额不足";
}
sourceAccountDO.setBalance(sourceAccountDO.getBalance().subtract(amount));
accountDAO.updateByPrimaryKeySelective(sourceAccountDO);
// error("annotation error!");
targetAccountDO.setBalance(targetAccountDO.getBalance().add(amount));
accountDAO.updateByPrimaryKeySelective(targetAccountDO);
return "转账成功!";
}
@Override
public String transferCode(Long sourceAccountId, Long targetAccountId, BigDecimal amount) {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
// 获取事务 开始业务执行
TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);
try {
AccountDO targetAccountDO = accountDAO.selectByPrimaryKey(targetAccountId);
AccountDO sourceAccountDO = accountDAO.selectByPrimaryKey(sourceAccountId);
if (null == sourceAccountDO || null == targetAccountDO) {
return "转入或者转出账户不存在";
}
error("code error");
if (sourceAccountDO.getBalance().compareTo(amount) < 0) {
return "转出账户余额不足";
}
sourceAccountDO.setBalance(sourceAccountDO.getBalance().subtract(amount));
targetAccountDO.setBalance(targetAccountDO.getBalance().add(amount));
accountDAO.updateByPrimaryKeySelective(sourceAccountDO);
accountDAO.updateByPrimaryKeySelective(sourceAccountDO);
// 提交事务
transactionManager.commit(transaction);
return "转账成功!";
} catch (Exception e) {
log.error("转账发生错误,开始回滚,source: {}, target: {}, amount: {}, errMsg: {}",
sourceAccountId, targetAccountId, amount, e.getMessage());
// 报错回滚
transactionManager.rollback(transaction);
}
return "转账失败";
}
@Override
public List<AccountDO> listAll() {
return accountDAO.selectAll();
}
private static void error(String msg) {
throw new RuntimeException(msg);
}
}
使用注解式事务,Spring会利用代理实现一个代理类,
然后从上下文中得到事务管理器,开启一个事务后执行业务代码,
如果满足你设置的回滚异常条件,就执行rollback
我们调用的时候是直接调用的Service的方法
但是Spring在实现的时候,实际是通过AOP Proxy(AOP 代理服务)来调用Transaction Advisor(做事务管理的)然后来处理调用注解式事务的service方法
o.s.web.servlet.DispatcherServlet : GET "/api/account/transfer/annotation?source=1&target=2&amount=123", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to io.ilss.transaction.onedatasource.web.AccountController#transferAnnotation(Long, Long, String)
o.s.j.d.DataSourceTransactionManager : Creating new transaction with name [io.ilss.transaction.onedatasource.service.impl.AccountServiceImpl.transferAnnotation]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; 'transactionManager',-java.lang.Exception
o.s.j.d.DataSourceTransactionManager : Acquired Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] for JDBC transaction
o.s.j.d.DataSourceTransactionManager : Switching JDBC Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] to manual commit
org.mybatis.spring.SqlSessionUtils : Creating a new SqlSession
org.mybatis.spring.SqlSessionUtils : Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
o.m.s.t.SpringManagedTransaction : JDBC Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] will be managed by Spring
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Parameters: 1(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey : <== Total: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42] from current transaction
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Parameters: 2(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey : <== Total: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42] from current transaction
i.i.t.o.d.A.updateByPrimaryKeySelective : ==> Preparing: update account SET nickname = ?, username = ?, `password` = ?, balance = ?, create_time = ?, update_time = ? where id = ?
i.i.t.o.d.A.updateByPrimaryKeySelective : ==> Parameters: 小一(String), xiaoyi(String), 123456(String), 877.00(BigDecimal), 2020-01-09T17:04:28(LocalDateTime), 2020-01-09T17:44:33(LocalDateTime), 1(Long)
i.i.t.o.d.A.updateByPrimaryKeySelective : <== Updates: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42] from current transaction
i.i.t.o.d.A.updateByPrimaryKeySelective : ==> Preparing: update account SET nickname = ?, username = ?, `password` = ?, balance = ?, create_time = ?, update_time = ? where id = ?
i.i.t.o.d.A.updateByPrimaryKeySelective : ==> Parameters: 小二(String), xiaoer(String), 123456(String), 223.00(BigDecimal), 2020-01-09T17:04:40(LocalDateTime), 2020-01-09T17:04:40(LocalDateTime), 2(Long)
i.i.t.o.d.A.updateByPrimaryKeySelective : <== Updates: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils : Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils : Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils : Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
o.s.j.d.DataSourceTransactionManager : Initiating transaction commit
o.s.j.d.DataSourceTransactionManager : Committing JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@185f0a96]
o.s.j.d.DataSourceTransactionManager : Releasing JDBC Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] after transaction
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["转账成功!"]
o.s.web.servlet.DispatcherServlet : Completed 200 OK
- GET 请求到 /api/account/transfer/annotation接口 然后调用service方法
- 根据写的Transactional注解的设置 创建一个新事务
- 选用JDBC连接 然后创建 SqlSession
- 为SqlSession注册事务同步
- SQL操作
- 然后把事务提交
- 最后释放资源。完成方法调用
- 接口返回200
通过日志可看出我们使用MyBatis+Druid 配置数据源 事务管理实际是使用的DataSourceTransactionManager.
虽然代码中指定了transactionManager,但实际却没有增加任何Bean注册或者其他有关DataSource的事务管理器代码。这个地方是因为Spring帮你做了,我设置transactionManager是因为自动装配的transactionManager名字就是这个。写出来提醒一下有这个配置,这个配置顾名思义就是配置对这个事务的管理器实现。简而言之就是PlatformTransactionManager的指定。后面多数据源的时候我们会通过指定不同的transactionManager来实现事务管理。
如果报错会是怎么样呢?
先看日志(开启DEBUG日志):
o.s.web.servlet.DispatcherServlet : GET "/api/account/transfer/annotation?source=1&target=2&amount=123", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to io.ilss.transaction.onedatasource.web.AccountController#transferAnnotation(Long, Long, String)
o.s.j.d.DataSourceTransactionManager : Creating new transaction with name [io.ilss.transaction.onedatasource.service.impl.AccountServiceImpl.transferAnnotation]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; 'transactionManager',-java.lang.Exception
o.s.j.d.DataSourceTransactionManager : Acquired Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] for JDBC transaction
o.s.j.d.DataSourceTransactionManager : Switching JDBC Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] to manual commit
org.mybatis.spring.SqlSessionUtils : Creating a new SqlSession
org.mybatis.spring.SqlSessionUtils : Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
o.m.s.t.SpringManagedTransaction : JDBC Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] will be managed by Spring
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Parameters: 1(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey : <== Total: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58] from current transaction
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey : ==> Parameters: 2(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey : <== Total: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58] from current transaction
i.i.t.o.d.A.updateByPrimaryKeySelective : ==> Preparing: update account SET nickname = ?, username = ?, `password` = ?, balance = ?, create_time = ?, update_time = ? where id = ?
i.i.t.o.d.A.updateByPrimaryKeySelective : ==> Parameters: 小一(String), xiaoyi(String), 123456(String), 754.00(BigDecimal), 2020-01-09T17:04:28(LocalDateTime), 2020-01-09T17:44:33(LocalDateTime), 1(Long)
i.i.t.o.d.A.updateByPrimaryKeySelective : <== Updates: 1
org.mybatis.spring.SqlSessionUtils : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils : Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils : Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
o.s.j.d.DataSourceTransactionManager : Initiating transaction rollback
o.s.j.d.DataSourceTransactionManager : Rolling back JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec]
o.s.j.d.DataSourceTransactionManager : Releasing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] after transaction
o.s.web.servlet.DispatcherServlet : Failed to complete request: java.lang.RuntimeException: annotation error!
o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is
java.lang.RuntimeException: annotation error!
.......
o.a.c.c.C.[Tomcat].[localhost] : Processing ErrorPage[errorCode=0, location=/error]
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error?source=1&target=2&amount=123", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 500
- GET 请求到 /api/account/transfer/annotation接口 然后调用service方法
- 根据写的Transactional注解的设置 创建一个新事务
- 选用JDBC连接 然后创建 SqlSession
- 为SqlSession注册事务同步
- SQL操作:可以从日志看到,执行到第一个跟新操作发生错误
- 直接回滚Rolling back JDBC transaction on Connection后打印错误日志。后面的第二个更新操作也就没了
- 方法异常退出,接口500
- 创建事务定义TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
- 设置事务属性:如传播属性、隔离属性等
- 通过TransactionManager开启事务
- 执行业务代码
- 提交事务 / 处理回滚
// todo: 下一篇多数据源事务管理