MyBatis中设置事务自动提交

MyBatis中设置事务自动提交

MyBatis框架是对JDBC的封装,MyBatis中的事务控制方式其本质也是JDBC的setAutoCommit()方法来设置事务提交的方式的。

1.MyBatis中事务提交

public class mybatisTest {
    @Test
    public void test01() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> list = mapper.findAll();
        for (User user : list) {
            System.out.println(user);
        }
        session.commit();
        session.close();
        is.close();
    }
}

2.上面试我们手动设置事务提交的,那么如何设置自动提交呢?

public class mybatisTest {
    @Test
    public void test01() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession(true);
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> list = mapper.findAll();
        for (User user : list) {
            System.out.println(user);
        }
        //session.commit();
        session.close();
        is.close();
    }
}

下面是源码SqlSessionFactory

public interface SqlSessionFactory {
  
    SqlSession openSession(boolean var1);
}

如果没有设置,默认是false,这时候我们需要手动设置事务提交了。如果我们设置了true那么就是自动提交了,是不是很简单。

你可能感兴趣的:(mybatis)