mybatis如果底层使用的是JDBC的话(mybatis.xml中配置的 transactionManager 标签的 type 设为 JDBC )
那么,mybatis会默认开启事务,也就是说,mybatis默认是关闭自动提交的。
在mybatis中,如果我们执行了数据库的修改操作(insert、update、delete),必须调用sqlSession.commit()方法,所做的修改才能持久化到磁盘。
在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(); } }
原文:https://www.cnblogs.com/IanIan/p/14289818.html