mybatis默認是開啟事務的
mybatis如果底層使用的是JDBC的話(mybatis.xml中配置的 transactionManager 標簽的 type 設為 JDBC )
那么,mybatis會默認開啟事務,也就是說,mybatis默認是關閉自動提交的。
在mybatis中,如果我們執行了數據庫的修改操作(insert、update、delete),必須調用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(); } }
