title: How solve the problem of that a message consumer try to retrieve an object that has not yet been inserted on DB?
body: <p>I am implementing a Saga.</p>
  <p>After a <code>SomthingCreated</code> event is published and then <code>Something</code> is retrieved on the other process.</p>
  <p>The problem is that <code>SomthingRepository.findById(somthingCreated.id())</code> returns null on the other process because the <code>Something</code> object is not inserted on DB yet.</p>
  <pre><code>@Transactional
  public String createSomething(long userId, String name) {
          
      String somethingId = somethingRepository.newSomethingId();
      Something something = new Something(userId, name);
      somethingRepository.save(something);
      System.out.println(&quot;save:&quot;+System.currentTimeMillis());
  
      return somethingId;
  }
  </code></pre>
  <p>the <code>SomthingCreated</code> event is published after save() using Aspect</p>
  <pre><code>@After(&quot;execution(* com.some.something.application.*.*(..))&quot;)
  public void publish() {
      DomainEventPublisher.instance().commitPublishing();
      System.out.println(&quot;publish:&quot;+System.currentTimeMillis());
  }
  </code></pre>
  <p>And then, the message consumer invokes application logic.</p>
  <pre><code>@Transactional
  public String handle(SomthingCreated somthingCreated) {
      System.out.println(&quot;handle:&quot;+System.currentTimeMillis());       
      Something something = somethingRepository.findById(somthingCreated.id());
      something.do(); //&lt;-- NULLPointerException
  }
  </code></pre>
  <p>I think
  The execution time is like this,<br />
  save:1643092272658<br />
  publish:1643092272852<br />
  handle:1643092272870<br />
  (the interval between <code>publish</code> and <code>handle</code> is faster than the interval between <code>save</code> and <code>publish</code> although the event passed the network!)</p>
  <p>What is that I am missing. I am using JPA and RabbitMQ on Spring.</p>
  <p>The repository is like this,</p>
  <pre><code>@Repository
  public class JpaSomethingRepository implements SomethingRepository {
  
      @PersistenceContext
      private EntityManager entityManager;
      
      @Override
      public void save(Something something) {
          entityManager.persist(something);
      }
  
  </code></pre>
  <p>How can I solve this problem?</p>
  <p>I could add sleep-method on handle-method and It works but It seems ugly.</p>
  <p>I am using entityManager.persist() with  @Transactional but why it is not inserted to DB in the same transaction?</p>
  <p>Thank you for your answer in advance.</p>