Mybatis failed to insert data when configuring insert
The error code is as follows:
@Test public void testInsertOne(){ SqlSession sqlSession = MyBatisUtils.getSession(); UserInfo userInfo = new UserInfo(); userInfo.setNickname("sunny"); userInfo.setPhoneNum("18936896033"); sqlSession.insert("insertUser", userInfo); LOG.log(Level.INFO, "userId:"+userInfo.getId()); sqlSession.close(); }
The reason is that the session was not committed but rolled back. The code is modified as follows:
@Test public void testInsertOne(){ SqlSession sqlSession = MyBatisUtils.getSession(); UserInfo userInfo = new UserInfo(); userInfo.setNickname("sunny"); userInfo.setPhoneNum("18936896033"); sqlSession.insert("insertUser", userInfo); sqlSession.commit(); //Note commit things LOG.log(Level.INFO, "userId:"+userInfo.getId()); sqlSession.close(); }
Source code interpretation: First look at several ways of openSession:
SqlSession openSession()SqlSession openSession(boolean autoCommit)SqlSession openSession(Connection connection)SqlSession openSession(TransactionIsolationLevel level)SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level)SqlSession openSession(ExecutorType execType)SqlSession openSession(ExecutorType execType, boolean autoCommit)SqlSession openSession(ExecutorType execType, Connection connection)
The difference can be seen from the first and second:
openSession() creates a thing, but it doesn't commit automatically
openSession(true) creates a thing and commits it automatically
openSession(Connection connection), does not use data element configuration, but a custom link
openSession(TransactionIsolationLevel level) The isolation level of the transaction:
(NONE,READ_UNCOMMITTED,READ_COMMITTED,REPEA TABLE_READ,SERIALIZA BLE)
openSession(ExecutorType execType):
ExecutorType.SIMPLE: This actuator type does nothing special. It creates a new preprocessed statement for each statement execution.
ExecutorType.REUSE: This executor type multiplexes preprocessed statements.
ExecutorType.BATCH: This executor will execute all update statements in batches and mark them as necessary if SELECT executes between them to ensure a simple and easy to understand behavior.