0

Step 1 In one thread, i fetched Employee for id 1 from DB in hibernate session and close the session

Step 2 I started session 2, Upadted the employee name for id 1.

Step 3 Now back in thread 1, i changed the employee name in detached instance.Then open the hibernate session and updated the emp in db

I was expectind concurrent update exception because in between version has been updated by thread 2. Why it is not thrown? I think i am missing some concept here but not sure what?

Here is the relevant code :-

Thread 1

    Step 1
    Employee Employee1=(Employee)session.get(Employee.class, 1);
    session.close();

    Step 2
    // Start new Thread i.e Thread 2 and update Employee in between
       Makes sure thread 2 is done before proceeding to step3


     Step 3
    Employee.setName("EmployeeUpdated");
    session = factory.openSession();
    tx = session.beginTransaction();
    session.update(Employee);
    tx.commit();// expect the concurrent update here
    session.close();

Thread 2

      Thread(SessionFactory factory){
           this.factory = factory; // same factory as used in Thread1
       }

      public  void run() {


    Session session  = factory.openSession();

    Transaction tx = session.beginTransaction();
    Employee Employee1=(Employee)session.get(Employee.class, 1);
    tx.commit();
    session.close();

    session = factory.openSession();
    tx = session.beginTransaction();
    Employee1.setName("EmployeeUpdatedByThread2");
    session.merge(Employee1);
    tx.commit();
    session.close();
}

Do hibernate need explict configuration to check version while update?

M Sach
  • 33,416
  • 76
  • 221
  • 314
  • Can you post your Employee entity so that we can confirm that it has a suitable property annotated with @Version. – Alex Barnes Mar 05 '14 at 14:28
  • I have not added any annotation @Version on any property.Does not hibernate do it internally(as per your question looks like hibernate need explicit @version)? I am under impression hibernate does the version check automatically without any explicit annotation/config setting. May be i am wrong. – M Sach Mar 05 '14 at 14:39
  • @Alex you are right. Hibernate does not support optimistic locking by default. http://stackoverflow.com/questions/6909035/how-to-do-optimistic-locking-in-hibernate also helped – M Sach Mar 05 '14 at 16:29
  • It does it by default, provided that you tell it which field to use to track the version. It's clever but not magic :) – Alex Barnes Mar 05 '14 at 16:59

1 Answers1

0

I need to add @Version on version property under object (where we to enable optimistic locking)to use optimistic locking.This Link helped a lot.

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314