为什么将自动提交设置为true? [英] Why set Autocommit to true?

查看:667
本文介绍了为什么将自动提交设置为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很长一段时间以来,我一直在想为什么JDBC API提供自动提交模式(java.sql.Connection.setAutocommit()).似乎很吸引人的麻烦只是诱使人们陷入麻烦.我的理论是,仅将其添加到JDBC是为了简化希望创建使用JDBC编辑和运行SQL的工具的供应商的生活.还有其他理由要启用自动提交吗?还是总是错误?

解决方案

不幸的是,使用自动提交是特定于数据库的(事务行为也是如此).我认为,如果您没有全局的程序化交易策略,那么自动提交可能比仅希望每个人都正确地关闭/回滚交易要好.

对于MySQL而言,默认情况下您可以将autocommit = true保持打开状态,并且在您开始交易时会自动将其关闭.设置autocommit = false的唯一原因是,如果有人尝试在没有BEGIN的情况下启动事务,则要强制执行错误.

为了简便起见,在当今的典型Java + MySQL应用程序中,我或多或少会忽略自动提交设置,使用打开会话中的视图"模式并将其命名为好".

我强烈建议不要使用显式RDBMS行锁,而应使用乐观锁. Hibernate提供了对乐观锁的内置支持,但这是一种易于使用的模式,甚至对于手动滚动的代码也可以采用,并且提供了更好的性能.

I have wondered for a long time why the JDBC API provides an autocommit mode (java.sql.Connection.setAutocommit()). It seems like an attractive nuisance that just lures people into trouble. My theory is it was only added to JDBC in order to simplify life for vendors who wanted to create tools for editing and running SQL using JDBC. Is there any other reason to turn on autocommit, or is it always a mistake?

解决方案

Unfortunately, using autocommit is database specific (as is transaction behavior). I think if you don't have a global, programmatic transaction strategy, autocommit is probably better than just hoping everyone properly closes/rolls back transactions.

Speaking for MySQL, you can leave autocommit=true on by default, and it will automatically turn that off when you BEGIN a transaction. The only reason to set autocommit=false is if you want to force an error if someone tries to start a transaction without a BEGIN.

For simplicity in a typical Java + MySQL application today, I would more or less ignore the auto-commit setting, use an open-session-in-view pattern and call it good.

I would strongly discourage explicit RDBMS row locks and use optimistic locks instead. Hibernate offers built-in support for optimistic locks, but it's an easy pattern to adopt even for hand-rolled code and offers better performance.

这篇关于为什么将自动提交设置为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆