title: Optimistic lock failed after REQUIRES_NEW transaction
body: <p>given the following scenario: two Spring beans, ServiceA and ServiceB, ServiceA loads an entity and then calls a method of bean ServiceB that loads and save the same entity.</p>
  <p>After ServiceB method is completed, transaction is committed and the entity version is moved from 1 to 2.
  After that call if I try to load again the same entity from ServiceA version is still 1.
  Of course this cause the following exception on save call in ServiceA:</p>
  <blockquote>
  <p>Optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)</p>
  </blockquote>
  <pre><code>@Service
  public class ServiceA {
  
      @Autowired
      private ServiceB serviceB;
  
      @Autowired
      private MyEntityRepository repo;
  
      @Transactional
      public void myMethod(Long id) {
          MyEntity e = repo.findById(id); -&gt; version 1
          serviceB.doStuff(id);
          e = repo.findById(id); -&gt; still version 1
          ...
          saveAndFlush(e); -&gt; optimistic lock error
      }
  }
  
  @Service
  public class ServiceB {
  
      @Autowired
      private MyEntityRepository repo;
  
      @Transactional(propagation = Propagation.REQUIRES_NEW)
      public void doStuff(Long id) {
          MyEntity e = repo.findById(id) -&gt; version 1
          ...
          repo.saveAndFlush(e); -&gt; version 2
      }
  }
  </code></pre>
  <p>The only way to make it work is detach entity in ServiceA after doStuff() call, but it looks a dirty solution. Is there a better solution for this?</p>
  <p>Used versions are:</p>
  <ul>
  <li>Hibernate: 5.4.6.FINAL</li>
  <li>Spring data JPA: 2.2.0.RELEASE</li>
  </ul>