EJB 事务锁/Hibernate 隔离级别

EJB Transaction locks / Hibernate isolation levels

我有一个网络服务可以在我的数据库中生成大量更新。之后,它会做一些其他的事情(比如微积分,调用另一个网络服务等)。最后,它再次联系数据库。

问题是表在整个 Web 服务生命周期内都处于锁定状态。因此,如果 "other things" 需要更长的时间,我这次无法使​​用表格。

有一种方法可以只锁定寄存器,而不是表吗?

如何避免这种情况?

我正在使用 Hibernate 和 MYSQL。

您使用的是什么事务隔离级别?请参阅 documentation 了解这如何影响锁定以及如何更改它。

检查您的申请。事务应尽可能短。如果需要,考虑重新设计。您甚至可以考虑使用 BASE instead of ACID.

Pro JPA 2 书说:

The reality is that very few applications actually need pessimistic locking, and those > that do only need it for a limited subset of queries. The rule is that if you think you need pessimistic locking, think again. If you are in a situation where you have a very high degree of write concurrency on the same object(s) and the occurrence of optimistic failures is high, then you might need pessimistic locking because the cost of retries can become so prohibitively expensive that you are better off locking pessimistically . If you absolutely cannot retry your transactions and are willing to sacrifice some amount of scalability for it, this also might lead you to use pessimistic locking.

所以我建议你再考虑一下你的需求。

i´m using PESSIMISTIC_WRITE

hibernate通过使用‘SELECT … FOR UPDATE‘语句获取独占锁(使用悲观锁时)

4:Connection.TRANSACTION_REPEATABLE_READ 锁定您选择的数据(交易期间)。所以你不需要使用 pessimistic_lock。 悲观锁通常用于repeateabe_read而事务隔离不是repeatable_read(Read Committed时)

以下链接描述了mysql锁定机制

https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html#isolevel_repeatable-read

There is a way to lock just the register, not the tables?

应该锁定所选行而不是表格(检查您的选择)