1

I have a scenario where I want to invalidate write operation. Briefing the scenario below:

There are two process running in altogether different systems and we have one common database. Let the process be termed as 'P1' and 'P2'. Each process can do read (R) and write (W) operaion. R1 and W1 show operation done by P1 and R2, W2 by P2. Lets take a common DB object (O).

Now operations are executing in following sequence :

R1 (read 'O' by process 'P1')
R2 (read 'O' by process 'P2')
W1 (write 'O' by process 'P1') -> this make 'O' of P2 dirty.
Now what I want is to fail P2 while performing its W2 operation as it contain old inconsistent object.

I have read few blogs of checking timestamp before persisting, but this is not the solution (as it is error prone even if it is matter of millisecs).
I want to know enterprise level solution.
Also I will like to know how it can be achieved by using 3rd party solution like hibernate.

Yogesh
  • 83
  • 2
  • 7
  • First of all do we talk about processes or threads? With threads and single JPA persistence unit check out this answer http://stackoverflow.com/a/25507470/3796586 – zbig Jan 21 '15 at 08:04
  • If we talk about processes you need to lock at the database level. – zbig Jan 21 '15 at 08:17

1 Answers1

1

You need optimistic locking. In hibernate you can provide optimistic locking with a separate numeric field annotated as @version for each entity. Each insert or update operation increments this field value by one and avoid stale data( with lower version value) from geting persisted to database.

Rohit
  • 2,132
  • 1
  • 15
  • 24
  • Thanks Rohit. One thing.. Let's say between R1 and W1, I do a write operation in db directly without changing "version" column, then W1 went successful. Is there any way we can achieve this? – Yogesh Jan 20 '15 at 11:04
  • This approach will work for operations only through same persistence context. – Rohit Jan 20 '15 at 12:24
  • If this solves your problem please mark this as answer. – Rohit Jan 21 '15 at 09:00