Mybatis配置insert时,插入数据失败

发布时间:2020-05-26 11:09:11 作者:sun2shadows
来源:网络 阅读:1542

错误代码如下:

@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):


推荐阅读:
  1. Mybatis在执行insert语句返回自增主键
  2. 怎么在mybatis中利用insert返回主键

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis insert

上一篇:扩容MySQL系统表空间的简单方法

下一篇:多角度看云计算的就业前景

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》