mybatis事務處理


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(); } }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM