简体   繁体   中英

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. This process doesn't use Hibernate to retrieve data for the sake of performance which sounds a bit far-fetched for me. This process also updates some fields of some objects from the collection using Hibernate.

Process 2 obtains an object similar to one of those in collection (basically the same row in DB) and updates it somehow. This process uses 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.

For example:

  1. process 1 obtains collection
  2. process 2 obtains one entity and removes some of its properties along with an entity it was linking to
  3. process 1 gets back and tries to save that entity and gets entity not found exception

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

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.

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.

I'd go for option 2 which would involve a version column in your entities. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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