mybatis 执行insert保存(提交事务)

上接:mybatis 执行insert保存(没提交事务)

提交事务

修改代码,在保存后需要执行sqlSession.commit();提交事务

@Test
@Test
public void save() throws IOException {
    /*
     1. 读取全局配置文件.
        getResourceAsStream 使用的资源路径
     */
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    // 2. 使用sqlSession的工厂构造器来读入全局配置,再生成一个sqlSession工厂.
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 3. 通过 sqlSession 工厂打开一个 sqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        //4 使用SqlSession创建Dao接口的代理对象
        IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

        User user=new User();
        //学习期间,放入测试数据
        user.setId("1004");
        user.setUsername("韩梅梅");
        user.setPassword("123456");
        user.setAge(20);
        user.setSex("0");
        user.setStatus("1");

        int num=mapper.save(user);
        sqlSession.commit();//全部正常执行后,提交事务
        System.out.println("更新了 "+num+" 条记录!");

    }catch (Exception e){
        e.printStackTrace();
        sqlSession.rollback();//抛异常(报错)时才回滚
    }finally{
//            sqlSession.commit();当抛出错误时,不应该提交事务了
        sqlSession.close();
    }
}

执行结果:


原文出处:/show_1EF6ZeKtfM1U.html