1、 手动提交事务
-
sqlSession.commit();
提交事务 -
sqlSession.rollback();
事务回滚
测试类中进行事务管理
@Test
public void insertStudent() {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
//1.当我们获取sqlSession对象时,就默认开启了事务
try{
//通过会话获取DAO对象
StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
//测试StudentDAO中的方法
Student student = new Student(0, "10005", "Lily", "女", 21);
int i = studentDAO.insertStudent(student);
//2.操作完成并成功之后,需要手动提交
sqlSession.commit();
}catch (Exception e){
//3.当操作出现异常,调用rollback进行回滚
sqlSession.rollback();
}
}
业务逻辑层手动事务管理
public class StudentServiceImpl implements StudentService {
public boolean addStudent(Student student) {
boolean b = false;
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try{
StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
int i = studentDAO.insertStudent(student);
b = i>0;
sqlSession.commit();
}catch (Exception e){
sqlSession.rollback();
}
return b;
}
}
2、自动提交事务
通过SqlSessionFactory调用openSession方法获取SqlSession对象时,可以通过参数设置事务是否自动提交:
如果参数设置为true,表示自定提交事务: factory.openSession(true);
如果参数设置为false,或者不设置参数,表示手动提交:factory.openSession();/factory.openSession(false);
MyBatisUtil优化
public class MyBatisUtil {
private static SqlSessionFactory factory;
private static final ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();
static{
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
factory = builder.build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getFactory(){
return factory;
}
private static SqlSession getSqlSession(boolean isAutoCommit){
SqlSession sqlSession = local.get();
if(sqlSession == null ){
sqlSession = factory.openSession(isAutoCommit);
local.set(sqlSession);
}
return sqlSession;
}
//手动事务管理
public static SqlSession getSqlSession(){
return getSqlSession(false);
}
//自动事务提交
public static <T extends Object>T getMapper(Class<T> c){
SqlSession sqlSession = getSqlSession(true);
return sqlSession.getMapper(c);
}
}
测试操作
@Test
public void testDeleteStudent() {
StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class);
int i = studentDAO.deleteStudent("10001");
}
业务逻辑层自动事务管理
public class StudentServiceImpl implements StudentService {
private StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class);
public boolean addStudent(Student student) {
int i = studentDAO.insertStudent(student);
boolean b = i>0;
return b;
}
}