I am just experimenting with optimistic blocking.
I have the following class:
@Entity public class Student { private Integer id; private String firstName; private String lastName; private Integer version; @Version public Integer getVersion() { return version; }
Now I get one of the students and try to update its properties at the same time.
Thread t1 = new Thread(new MyRunnable(id)); Thread t2 = new Thread(new MyRunnable(id)); t1.start(); t2.start();
and inside MyRunnable:
public class MyRunnable implements Runnable { private Integer id; @Override public void run() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Student student = (Student) session.load(Student.class, id); student.setFirstName("xxxx"); session.save(student); session.getTransaction().commit(); System.out.println("Done"); } public MyRunnable(Integer id){ this.id = id; } }
what happens when the first transaction update object succeeds and the second transaction throws:
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.vanilla.entity.Student
This is normal.
My question is: 1) What should I do if I want the second transaction to do nothing and not cause any exceptions.
2) What should I do if I want the second transaction to overlap the data updated by the first transaction.
Thanks.
source share