title: How to ensure @Entity exists in @Async methods?
body: <p>I want to create an entity, and within the transaction trigger an <code>@Async</code> method to perform some changes on the same entity. The changes should also be persisted async.</p>
  
  <p>Problem: as I have to fire the async method within the transaction, I could use the autogenerated <code>@Id</code> from the entity. BUT the async method then would have to first fetch the entity by that Id, and most often this does not exist yet.</p>
  
  <p>Only if I put some <code>Thread.sleep()</code> as first statement inside the async method, it can mostly be ensured that the entity has been persisted by the outer transaction.</p>
  
  <p>But that solution is not very nice. Question: how can I ensure inside the async method that it should wait for the entity to exist in DB?</p>
  
  <pre><code>@Service
  public class OuterService {
      @Service
      private SyncService service;
  
      @Transactional
      public void process() {
          service.mySyncMethod();
          //etc
      }
  }
  
  @Service
  public class SyncService {
      @Transactional
      public void mySnycMethod() {
          Entity entity = new MyEntity();
          //fill entity
          dao.save(entity);
          asyncService.performLongRunningTask(entity.getId());
      }
  }
  
  @Service
  public class AsycnService {
      @Async
      @Transactional
      public voi performLongRunningTask(Long id) {
          //problem: is mostly == null because this is executed before the outer transaction completes
          //only works if I put like Thread.sleep(5000) in between. but how can I really ensure the entity exists before executing this async lookup?
          MyEntity entity = dao.findOne(id);
  
          //perform long running task
          //change some fields in entity accordingly
          dao.save(entity);
      }
  }
  </code></pre>