温馨提示×

温馨提示×

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

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

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

发布时间:2020-05-26 11:09:11 来源:网络 阅读:1540 作者:sun2shadows 栏目:软件技术

错误代码如下:

@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 在它们中间执行还会标定它们是 必须的,来保证一个简单并易于理解的行为。


向AI问一下细节

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

AI