简体   繁体   English

同一实体的并发更新

[英]Concurrent updates of same entity

Gentlemen/ladies, 先生们/女士们,

I've got a problem with concurrent updates of the same entity. 我对同一个实体的并发更新有问题。

Process 1 obtains collection of objects. 流程1获取对象的集合。 This process doesn't use Hibernate to retrieve data for the sake of performance which sounds a bit far-fetched for me. 为了提高性能,此过程不使用Hibernate来检索数据,这对我来说有点牵强。 This process also updates some fields of some objects from the collection using Hibernate. 此过程还使用Hibernate更新了集合中某些对象的某些字段。

Process 2 obtains an object similar to one of those in collection (basically the same row in DB) and updates it somehow. 流程2获得一个与集合中的对象相似的对象(基本上是DB中的同一行),并以某种方式对其进行更新。 This process uses Hibernate. 此过程使用Hibernate。

Since process 1 and process 2 don't know about each other they can update the same entity, leaving it in non-consistent state. 由于进程1和进程2彼此不了解,因此他们可以更新同一实体,从而使其处于不一致状态。

For example: 例如:

  1. process 1 obtains collection 流程1获取集合
  2. process 2 obtains one entity and removes some of its properties along with an entity it was linking to 流程2获得一个实体,并删除其某些属性以及链接到的实体
  3. process 1 gets back and tries to save that entity and gets entity not found exception 进程1返回并尝试保存该实体,并获取未找到的实体异常

I need to deal with this situation. 我需要处理这种情况。

So what can be done? 那该怎么办呢?

For now I see two ways: 现在,我看到两种方法:

  1. create layer above database that will keep track of every entity in the system effectively prohibiting from creating multiple instances of same entity 在数据库上方创建一个层,该层将跟踪系统中的每个实体,从而有效地禁止创建同一实体的多个实例
  2. set up optimistic locks and since some entities are not obtained by Hibernate I need to implement it somehow different 设置乐观锁,由于Hibernate无法获得某些实体,因此我需要以某种方式实现它

Any ideas would be very helpful 任何想法都将非常有帮助

Thanks in advance 提前致谢

Since process 1 and process 2 don't know about each other they can update the same entity, leaving it in non-consistent state. 由于进程1和进程2彼此不了解,因此他们可以更新同一实体,从而使其处于不一致状态。

I'd reformulate that: both processes can update the same data . 我将这样重新表述:两个进程都可以更新相同的数据 Only Hibernate would know the entities while the other process seems to access the data via JDBC. 只有Hibernate知道实体,而其他进程似乎通过JDBC访问数据。

I'd go for option 2 which would involve a version column in your entities. 我会选择选项2,它会在您的实体中涉及版本列。 IIRC Hibernate would then add a WHERE version = x condition to the queries and check whether all rows have been updated and if not an OptimistictLockException would be thrown. 然后,IIRC Hibernate将向查询中添加WHERE version = x条件,并检查是否所有行都已更新,否则将引发OptimistictLockException You could do the same in your JDBC queries, ie UPDATE ... SET ... version = x + 1 ... WHERE version = x AND additionalConditions and check the number of updates rows that is returned by JDBC. 您可以在JDBC查询中执行相同的操作,即UPDATE ... SET ... version = x + 1 ... WHERE version = x AND additionalConditions并检查JDBC返回的更新行数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM