java 为什么在将 FK 添加到 DB 后,myBatis 插入/更新功能现在需要提交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4372640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:04:43  来源:igfitidea点击:

why do myBatis insert/update functions now require a commit after adding FK to DB?

javamysqlmybatisibatis

提问by clarson

i have a project that uses myBatis for persistence. method "A" below was working just fine until I added some foreign keys and converted my table from myISAM to innoDB. After the conversion, method "A" would fail silently, not even a warning in the logs. After the conversion, only method "B" does a successful insert. Both methods write the correct sql to the logs, but only "B" works.

我有一个使用 myBatis 进行持久化的项目。下面的方法“A”工作得很好,直到我添加了一些外键并将我的表从 myISAM 转换为 innoDB。转换后,方法“A”将无声地失败,甚至日志中都没有警告。转换后,只有方法“B”才能成功插入。两种方法都将正确的 sql 写入日志,但只有“B”有效。

Can anyone fill me in on why i need to do a commit now, but did not have to do a commit previously?

谁能告诉我为什么我现在需要提交,但以前不必提交?

//doesnt work, but worked previously
public void A(Role role) {
    SqlSession session = sqlSessionFactory.openSession();
    try {
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        mapper.updateByPrimaryKeySelective(role);
    }catch(Exception e){
        logger.error(e);
    } finally {
        session.close();
    }
    return;
}

//works correctly, but why?
public void B(Role role) {
    SqlSession session = sqlSessionFactory.openSession();
    try {
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        mapper.updateByPrimaryKeySelective(role);
        session.commit();
    }catch(Exception e){
        logger.error(e);
    } finally {
        session.close();
    }
    return;
}

回答by AngerClown

myISAM is not transactional. Autocommit is on by default (actually it's ignored by the JDBC driver since every statement commits). innoDB is transactional and autocommit is also off by default. This means you have to call session.commit() or the DB never actually does the update.

myISAM 不是事务性的。默认情况下自动提交是打开的(实际上它被 JDBC 驱动程序忽略,因为每个语句都提交了)。innoDB 是事务性的,默认情况下自动提交也是关闭的。这意味着您必须调用 session.commit() 或 DB 从未真正进行更新。

See this blog entryfor more information.

有关更多信息,请参阅此博客条目

Note that you should call commit rather than leave things up to autocommit. Leaving autocommit off will cause problems with connection pooling since it can leave statements in an unknown state when the connection is reused.

请注意,您应该调用 commit 而不是将事情留给自动提交。关闭自动提交会导致连接池出现问题,因为当连接被重用时,它会使语句处于未知状态。