Home Is optimistic locking work by default in hibernate?
Reply: 0

Is optimistic locking work by default in hibernate?

user1792
1#
user1792 Published in June 20, 2018, 7:34 am

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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.325528 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO