Hibernate和事务和表锁定 [英] Hibernate and transactions and table locking

查看:294
本文介绍了Hibernate和事务和表锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的代码如下所示:

  beginTransaction(); 
//发生很多事情,可能需要几分钟到几分钟的时间。
//它将通过调用惰性关系中的getter方法从几个表中读取。
commitTransaction();

在开始和提交之间,正在读取的表被锁定,随后会如果上述相同的代码被另一个用户调用,会在多用户环境中引发问题?

如果上述问题存在问题,我们是否应该总是尝试并保持交易短?并且为了促进这一点,而不是在懒惰关系上调用getter方法,这是否意味着尽量保持交易的简短性并为父母的孩子手动找到它们?\\ b $ b

解决方案

Hibernate不会执行任何操作来显式锁定您读取的表。答案真的取决于你正在使用的数据库以及你的隔离级别设置为什么。通过阅读行来锁定整个不应该发生在本世纪编写的任何全功能数据库中。对于任何多版本数据库,除非您明确地自行锁定该行,否则没有任何东西会被锁定。



您的事务应该是您的原子工作单元需要的长度。没有正确或错误的长度。问问你自己:这里发生的所有事情是否成功或失败,如果任何一件失败,都会一起回滚?这是您设置交易的范围。



请记住,您不需要事务来进行延迟加载!你只需要一个开放的会议。这两者没有联系。你可以提交你的交易,并保持你的会话打开,以延迟加载工作。


If I have code that looks like the following:

beginTransaction();
// lots of stuff happens, can take anywhere from a minute to several minutes.
// it will read from several tables via calling getter methods on lazy relationships.
commitTransaction();

In between the begin and commit, are the tables that are being read from being locked and subsequently will this cause problems in a multi-user environment where issues will occur when the same code above is called by another user?

If the above is problematic, should we always try and keep transactions short? and to facilitate this, instead of calling getter methods on lazy relationships, does that mean its best to keep the transactions short and do finds manually for the children of the parents?

解决方案

Hibernate is not going to do anything to explicitly lock tables you read from. The answer really depends on what Database you're using and what your isolation levels are set to. Locking an entire table by reading rows shouldn't happen in any full featured database written in this century. For any multiversioning database, nothing is going to get locked unless you explicitly lock the row yourself.

Your transactions should be whatever length they need to be for your atomic unit of work. There's no right or wrong length. Ask yourself "does everything that happens here succeed or fail as a single unit and all get rolledback together if any one piece fails?" That's the scope you set a transaction for.

Remember, you do not need a transaction to have lazy loading! You just need an open Session. The two are not linked. You can commit your transaction and keep your session open to keep lazy loading working.

这篇关于Hibernate和事务和表锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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