title: Optimistic locking and org.hibernate.StaleObjectStateException:
body: <p>I'm just experimenting with Optimistic locking.</p>
  
  <p>I have the following class:</p>
  
  <pre><code>@Entity
  public class Student {
  
      private Integer id;
      private String firstName;
      private String lastName;
      private Integer version; 
  @Version
      public Integer getVersion() {
          return version;
      }
  
  //all other getters ommited.
  }
  </code></pre>
  
  <p>now I'm fetching one of the students and try to update its properties concurrently.</p>
  
  <pre><code>Thread t1 = new Thread(new MyRunnable(id));
      Thread t2 = new Thread(new MyRunnable(id));
      t1.start();
      t2.start();
  </code></pre>
  
  <p>and inside of MyRunnable:</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>what is happening that first transaction updates object successfully and second transaction throws:</p>
  
  <pre><code>org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.vanilla.entity.Student#1]
  </code></pre>
  
  <p>This is ok.</p>
  
  <p>My question is: 
  1) What should I do if I want second transaction to do nothing and not throw any exception.</p>
  
  <p>2) What should I do if I want second transaction to override data updated by first transaction. </p>
  
  <p>Thanks.</p>