mybatis Transaction Rollback Configuration Action
- 2021-08-28 20:07:42
- OfStack
In mybatis batch operation, when inserting multiple pieces of data, set rollback, but the previous pieces are still inserted. After trying
The problem is:
openSession (false) on the official website api can be rolled back, but it is still true to view it with session. getConnection (). getAutoCommit ()
Solution:
Change DataSource configuration to AutoCommit (false)
Set setAutoCommit (false) to conn, and submit and roll back with conn
Examples:
SqlSession session = sqlSessionFactory.openSession(false);
Connection conn = session.getConnection();
conn.setAutoCommit(false);
try {
UserMapper mapper = session.getMapper(UserMapper.class);
for (String name : names) {
// Various operations
User user = new User();
user.setName(name);
// Insert, require rollback
mapper.insert(user);
}
conn.commit();
} catch (Exception e) {
// There are repeated rollbacks
conn.rollback();
throw e;
} finally {
session.close();
}
Added: Spring Boot + Mybatis Plus manually triggers transaction rollback
Using the first method (omitting the code of database operation) to operate the transaction of Mybatis Plus, if there is an exception entering catch, the database operation will not be rolled back, but the error of No transaction aspect-managed TransactionStatus in scope will be reported instead. Modify to the second method to manage and roll back the transaction normally
See an explanation for this situation:
The @ Transactional must trigger the aop proxy to take effect, so the non-public method does not execute a transaction, and the public method is referenced in this class and does not execute a transaction
Method 1:
@PostMapping("/save1")
public boolean action01() {
return action00();
}
@PostMapping("/save2")
public boolean action02() {
return action00();
}
@Transactional
private boolean action00() {
String result = true;
try {
System.out.println(1/0);
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
result = false;
}
return result;
}
Method 2:
@PostMapping("/save1")
@Transactional
public boolean action01() {
boolean result = action00();
if (!result){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return result;
}
@PostMapping("/save2")
@Transactional
public boolean action02() {
boolean result = action00();
if (!result){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return result;
}
private boolean action00() {
String result = true;
try {
System.out.println(1/0);
} catch (Exception e) {
result = false;
}
return result;
}