mybatis设置自动提交事务

我们想要mybatis帮助我们自动提交事务其实很简单,只需要在SqlSessionFactory对象的openSession方法中设置参数为true就可以了,mybatis工具类如下:

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用Mabatis第一步:获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //有了SqlsessionFactory,我们就可以从中获得SqlSession的实例了。
    public static SqlSession getSqlSession(){

        return sqlSessionFactory.openSession(true); //如果不设置参数或者参数为false就是手动提交事务,参数设置为true就是自动提交事务
    }
}

 

自动提交事务有什么用?

在以前我们没有给openSession设置参数的时候,默认是手动提交事务。这样我们进行增删改操作的时候就需要手动提交事务,如下边第7行代码就是提交事务

1 @Test
2     public void addUser(){
3         SqlSession sqlSession = MybatisUtils.getSqlSession();
4         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
5         int res = mapper.addUser(new User(6, "王五", "789456"));
6         System.out.println("res:"+res);
7         sqlSession.commit();
8         sqlSession.close();
9     }

 

 现在我们给openSession设置参数为true之后,mybatis就帮我们自动提交事务

1 @Test
2     public void addUser(){
3         SqlSession sqlSession = MybatisUtils.getSqlSession();
4         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
5         int res = mapper.addUser(new User(6, "王五", "789456"));
6         System.out.println("res:"+res);
7         sqlSession.close();
8     }

 

posted @ 2020-03-16 16:31  白熊啊  阅读(17124)  评论(0编辑  收藏  举报