阅读本文大概需要 6.5 分钟。
因此,记住事务的三个真实存在的方法,不要被各种事务状态名词所迷惑,它们分别是:conn.setAutoCommit()、conn.commit()、conn.rollback()。
1. Mybaits中的事务接口Transaction
Connection getConnection() throws SQLException;
void commit() throws SQLException;
void rollback() throws SQLException;
void close() throws SQLException;
}
public void close() throws SQLException {
if (connection != null) {
resetAutoCommit();
if (log.isDebugEnabled()) {
log.debug(“Closing JDBC Connection [“ + connection + “]”);
}
connection.close();
}
}
2. 事务工厂TransactionFactory
3. Transaction的用法
SqlSession sqlSession = MybatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName(“yy”);
student.setEmail(“email@email.com”);
student.setDob(new Date());
student.setPhone(new PhoneNumber(“123-2568-8947”));
studentMapper.insertStudent(student);
sqlSession.commit();
} catch (Exception e) {
sqlSession.rollback();
} finally {
sqlSession.close();
}
}
关注公众号「程序员的成长之路」后回复「2048」关键字,免费获取5T技术学习资源!包括但不限于:C/C++,Linux,Python,Java,PHP,人工智能,单片机,树莓派,等等。
4. 你可能关心的有关事务的几种特殊场景表现(重要)
SqlSession sqlSession = MybatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName(“yy”);
student.setEmail(“email@email.com”);
student.setDob(new Date());
student.setPhone(new PhoneNumber(“123-2568-8947”));
studentMapper.insertStudent(student);
// 提交
sqlSession.commit();
studentMapper.insertStudent(student);
// 多次提交
sqlSession.commit();
} catch (Exception e) {
// 回滚,只能回滚当前未提交的事务
sqlSession.rollback();
} finally {
sqlSession.close();
}
studentMapper.insertStudent(student);
} finally {
sqlSession.close();
}
public void close() {
try {
executor.close(isCommitOrRollbackRequired(false));
dirty = false;
} finally {
ErrorContext.instance().reset();
}
}
return (!autoCommit && dirty) || force;
}
public int insert(String statement, Object parameter) {
return update(statement, parameter);
}
@Override
public int update(String statement, Object parameter) {
try {
dirty = true;
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.update(ms, wrapCollection(parameter));
} catch (Exception e) {
throw ExceptionFactory.wrapException(“Error updating database. Cause: “ + e, e);
} finally {
ErrorContext.instance().reset();
}
}
public void commit(boolean force) {
try {
executor.commit(isCommitOrRollbackRequired(force));
dirty = false;
} catch (Exception e) {
throw ExceptionFactory.wrapException(“Error committing transaction. Cause: “ + e, e);
} finally {
ErrorContext.instance().reset();
}
}
推荐阅读:
“一键删除中国App”应用海外走红,下载量破500万!谷歌:我先把你删除了
微信扫描二维码,关注我的公众号
朕已阅
文章收集整理于网络,请勿商用,仅供个人学习使用,如有侵权,请联系作者删除,如若转载,请注明出处:http://www.cxyroad.com/1141.html