首页 > 其他 > 详细

mybatis事务处理

时间:2021-01-17 21:41:58      阅读:44      评论:0      收藏:0      [点我收藏+]

mybatis默认是开启事务的

 

mybatis如果底层使用的是JDBC的话(mybatis.xml中配置的 transactionManager 标签的 type 设为 JDBC 

那么,mybatis会默认开启事务,也就是说,mybatis默认是关闭自动提交的。

在mybatis中,如果我们执行了数据库的修改操作(insertupdatedelete),必须调用sqlSession.commit()方法,所做的修改才能持久化到磁盘。

如何设置mybatis开启自动提交(关闭事务)

  在openSession()时,传入true,即可关闭事务。 openSession(true)

 

 

例子:

UserMapper.xml  , 配置delete命令

    <delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id = #{id}
    </delete>
测试
    /**
     * 通过id删除用户
     */
    @Test
    public void deleteUserById(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.deleteUserById(4);
sqlSession.commit();
if (i > 0){ System.out.println("删除成功"); System.out.println("***********************************************"); List<User> userList = mapper.getUserList(); for (User use:userList) { System.out.println(use); } }else { System.out.println("删除失败"); } } catch (Exception e) { e.printStackTrace(); } finally { //关闭sqlSession sqlSession.close(); } }

 

 

mybatis事务处理

原文:https://www.cnblogs.com/IanIan/p/14289818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!