mirror of
https://gitee.com/mybatis-flex/mybatis-flex.git
synced 2025-12-07 17:18:24 +08:00
refactor: optimize FlexSpringTransaction
This commit is contained in:
parent
c51504ed03
commit
1e3476fc18
@ -16,6 +16,8 @@
|
||||
package com.mybatisflex.spring;
|
||||
|
||||
import com.mybatisflex.core.datasource.FlexDataSource;
|
||||
import com.mybatisflex.core.transaction.TransactionContext;
|
||||
import com.mybatisflex.core.util.StringUtil;
|
||||
import org.apache.ibatis.transaction.Transaction;
|
||||
|
||||
import java.sql.Connection;
|
||||
@ -30,6 +32,9 @@ import java.sql.SQLException;
|
||||
public class FlexSpringTransaction implements Transaction {
|
||||
|
||||
private final FlexDataSource dataSource;
|
||||
private Boolean isConnectionTransactional;
|
||||
private Boolean autoCommit;
|
||||
private Connection connection;
|
||||
|
||||
public FlexSpringTransaction(FlexDataSource dataSource) {
|
||||
this.dataSource = dataSource;
|
||||
@ -37,22 +42,41 @@ public class FlexSpringTransaction implements Transaction {
|
||||
|
||||
@Override
|
||||
public Connection getConnection() throws SQLException {
|
||||
return dataSource.getConnection();
|
||||
if (isConnectionTransactional == null) {
|
||||
connection = dataSource.getConnection();
|
||||
isConnectionTransactional = StringUtil.isNotBlank(TransactionContext.getXID());
|
||||
autoCommit = connection.getAutoCommit();
|
||||
return connection;
|
||||
}
|
||||
// 非事务
|
||||
else if (!isConnectionTransactional) {
|
||||
return connection;
|
||||
}
|
||||
// 在事务中
|
||||
else {
|
||||
return dataSource.getConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commit() throws SQLException {
|
||||
getConnection().commit();
|
||||
if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) {
|
||||
this.connection.commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rollback() throws SQLException {
|
||||
getConnection().rollback();
|
||||
if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) {
|
||||
this.connection.rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SQLException {
|
||||
getConnection().close();
|
||||
if (this.connection != null && !this.isConnectionTransactional) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user