1. 程式人生 > 實用技巧 >Mybatis自動提交失敗:Setting autocommit to false on JDBC Connection

Mybatis自動提交失敗:Setting autocommit to false on JDBC Connection

報錯:


今天在使用Mybatis進行新增資料的時候,發現自己的SQL語句沒有問題!但是資料就是新增不到資料庫?經過一番搜尋發現,Mybatis預設情況下開啟的是手動提交, 我們需要開啟自動提交!

方法:

  1. 使用SqlSession物件呼叫commit()方法;
@Before
public  void init() throws Exception {
        input = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input);
        sqlSession =factory.openSession();
        userDao = sqlSession.getMapper(IUserDao.class);
        sqlSession.commit();
    }
  1. openSession()方法里加上 true引數
@Before
    public  void init() throws Exception {
        input = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input);
        sqlSession =factory.openSession(true);
        userDao = sqlSession.getMapper(IUserDao.class);
    }