title: Optimistic Lock - Concurrency issue with Hibernate
body: <p>I am trying to understand what <code>Optimistic Lock</code> in <code>Hibernate</code> does and how is it to be used properly. </p>
  
  <p>My first question is whether it only cares that an exception is thrown when one <code>Thread</code> tries to persist an <code>Object</code> while another has in the meantime already changed the state of the same <code>Object</code>, or does it care that both modifications are saved correctly? Is the last at least true when chains of Objects are updated and the parts which each <code>Thread</code> tries to alter are different?</p>
  
  <p>I would like to present an example in order to make my question on a true scenario comprehensible. It is a bad-designed <code>database-model</code> but it serves to depict the issue:</p>
  
  <p>Assuming one has the following Entities:</p>
  
  <pre><code>@Entity
  public class Order{
  
  @OneToMany
  private User_Order user_Order;
  
  }
  
  
  @Entity
  public class User_Order{
  
  @OneToMany
  private Product product;
  
  }
  </code></pre>
  
  <p>In words an <code>Order</code> holds a number of <code>User-Orders</code> and each <code>User-Order</code> has a number of <code>Products</code>. Assuming that each Thread excecutes the following code:</p>
  
  <pre><code>Order order = (Order) session.get(Order.class, 1);
  //some other code...
  Set&lt;User_Order&gt; userOrders = order.getUserOrder();
  User_Order myUserOrder = //find my User_Order
  List&lt;Products&gt; products = myUserOrder.getProducts();
  //modify myUserOrder 
  //modify products
  session.update(order);
  </code></pre>
  
  <p>It is apparent that if a Thread updates the <code>Object</code> <code>order</code>, then the data which was persisted by other Threads return to its initial state, because the last Thread does not know anything about the update. (As already admitted, it is the result of a bad-designed <code>database-model</code>) </p>
  
  <p>1) What is the best way to ensure concurrency safety in case that several <code>Threads</code> can excecute this code simultaneously ? Can an <code>Optimistic Lock</code> be applied here? </p>
  
  <p>2) What is the answer to the previous question if one <code>Thread</code> (User) can modify also the data of which theoritically belong to other Users? </p>