Search code examples
javahibernateconcurrentmodification

Is optimistic locking work by default in hibernate?


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?


Solution

  • 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.