错误代码如下:
@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();
}
原因是会话没有被提交而是被回滚了,修改代码如下:
@Test
public void testInsertOne(){
SqlSession sqlSession = MyBatisUtils.getSession();
UserInfo userInfo = new UserInfo();
userInfo.setNickname("sunny");
userInfo.setPhoneNum("18936896033");
sqlSession.insert("insertUser", userInfo);
sqlSession.commit(); //注意提交事物
LOG.log(Level.INFO, "userId:"+userInfo.getId());
sqlSession.close();
}
源码解读:首先看看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)
从地一个和第二个就可看出区别:
openSession()会创建一个事物,但是不会自动提交
openSession(true)会创建一个事物,并自动提交
openSession(Connection connection),不使用数据元配置,而是自定义的一个链接
openSession(TransactionIsolationLevel level)事物的隔离级别:
(NONE,READ_UNCOMMITTED,READ_COMMITTED,REPEA TABLE_READ,SERIALIZA BLE)
openSession(ExecutorType execType):
ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情。它为每个语句的执行创建一个新的预处理语句。
ExecutorType.REUSE: 这个执行器类型会复用预处理语句。
ExecutorType.BATCH: 这个执行器会批量执行所有更新语句,如果 SELECT 在它们中间执行还会标定它们是 必须的,来保证一个简单并易于理解的行为。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。