8

I have developed a customer maintenance application. Users can alter the customer details via web interface. I want to handle the following scenario:

  1. User 1 loads customer1 details.
  2. User 2 loads customer1 details.
  3. User 1 changes and saves customer1's name.
  4. User 2 only changes and saves customer1's age.

In the scenario above, finally database holds customer1's old name and the new age because User 2 overwrites User 1's update. I'm using Hibernate. I had heard that Hibernate Automatic Versioning supports this. If any one know how to handle this please advise me.

Behrang
  • 46,888
  • 25
  • 118
  • 160
Niroshan Abayakoon
  • 913
  • 1
  • 10
  • 22

2 Answers2

13

You just need to add a field annotated with @Version:

public class Customer {

 @Id
 private Long id;

 @Version
 private Long version;

 // rest of the fields, etc.

}

Read this article for more information.

Behrang
  • 46,888
  • 25
  • 118
  • 160
  • I use SpringJDBC over any ORM in my Java Project. But I need to add some Hibernate's @Version functionality, to prevent some situation like discribed there. So maybe you can suggest me JDBC realization? – MeetJoeBlack Feb 17 '16 at 22:51
  • The general term for this approach is called _optimistic locking_. You can find some guidance here: http://stackoverflow.com/a/8880896/309683 – Behrang Feb 18 '16 at 10:35
0

one solution, when second request tends to update details first check if it is updated after details loaded, if so then raise exception and allow user to change after loading details again, you can use modification time stamp to compare

Nirmal- thInk beYond
  • 11,847
  • 8
  • 35
  • 46