【发布时间】:2021-06-07 00:18:38
【问题描述】:
我找到了在提交失败时回滚事务的解决方案,并且效果很好。 但是你能解释一下为什么先调用 Autorollback 对象关闭方法而不是连接关闭吗?
自动回滚类:
public class AutoRollback implements AutoCloseable {
private Connection conn;
private boolean committed;
public AutoRollback(Connection conn){
this.conn = conn;
}
public void commit() throws SQLException {
conn.commit();
committed = true;
}
@Override
public void close() throws SQLException {
if(!committed) {
conn.rollback();
}
}
}
使用自动回滚的服务方法示例:
try(Connection connection = MySQLDAOFactory.getConnection();
AutoRollback autoRollback = new AutoRollback(connection)){
result = carDao.insertCar(connection,car);
autoRollback.commit();
} catch (SQLException | NamingException | MySQLEXContainer.MySQLDBExecutionException throwables) {
throw new ApplicationEXContainer.ApplicationCanNotChangeException(throwables.getMessage(),throwables);
}
为什么Autorollback的close方法会起作用?如果连接关闭了怎么调用rollback方法呢?所以唯一的解释是autorollback close方法在连接关闭之前被调用,但是为什么呢?
【问题讨论】:
标签: java mysql database-connection try-with-resources autocloseable