成都网站建设设计

将想法与焦点和您一起共享

Mybatis配置insert时,插入数据失败-创新互联

错误代码如下:

创新互联是一家专注网站建设、网络营销策划、微信小程序、电子商务建设、网络推广、移动互联开发、研究、服务为一体的技术型公司。公司成立十载以来,已经为数千家建筑动画各业的企业公司提供互联网服务。现在,服务的数千家客户与我们一路同行,见证我们的成长;未来,我们一起分享成功的喜悦。
@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 在它们中间执行还会标定它们是 必须的,来保证一个简单并易于理解的行为。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


新闻名称:Mybatis配置insert时,插入数据失败-创新互联
文章源于:http://chengdu.cdxwcx.cn/article/dgshcs.html