title: JPA: OptimisticLockException and Cascading
body: <p>In my current project I use Spring Data JPA with Hibernate but consider this as a more general question that should also cover "plain" JPA.</p>
  
  <p>I'm uncertain how I should deal with <code>OptimisticLockException</code> when using <code>@Version</code>.</p>
  
  <p>Due to how my application works some relationships have <code>CascadeType.PERSIST</code> and <code>CascadeType.REFRESH</code>, others also have <code>CascadeType.MERGE</code>.</p>
  
  <ol>
  <li>Where to handle <code>OptimisticLockException</code></li>
  </ol>
  
  <p>As far as I can tell handling this on the service layer won't work especially with <code>CascadeType.MERGE</code> because then the offending entity could be one that needs to be handled by another service ( I have a service per entity class).</p>
  
  <p>Problem is I'm creating a framework and hence there is no layer above service so I could just "delegate" this to the user of my framework but that seems "weak and lazy".</p>
  
  <ol>
  <li>Determine offending entity and fields that changed</li>
  </ol>
  
  <p>if a OptimisticLockException occurs, how do I get which entity caused the issue and what fields were changed? </p>
  
  <p>Yes, i can call <code>getEntity()</code> but how do I cast that to the correct Type especially if CascadeType.MERGE was used? The entity could be of multiple types, so a if/switch with <code>instanceof</code> comes to mind but this seems ugly like hell.</p>
  
  <p>Once I have the correct type I would need to get all the differences between the versions excluding certain fields like version itself or lastModifiedDate.</p>
  
  <p>In the back of my mind is also HTTP 409 which stated that in case of conflict response should contain the conflicting fields. </p>
  
  <p>Is there a "best-practice-pattern" for all this?</p>