title: Invoke flush() on a repository or service layer?
body: <p>For example I have the following classes</p>
  
  <pre><code>@Repository
  public class JpaUserRepository implements UserRepository {
      ...
      public void create(User user) {
          entityManager.persist(user);
      }
  }
  
  @Trensactional
  public class UserServiceImpl implements UserService {
      ...
      public void register(User user) {
          try {
              repository.create(user);
          } catch (DataIntegrityViolationException ex) {
              throw new UserAlreadyExistException(user);
          }
      }
  }
  </code></pre>
  
  <p>There is a problem with this approach. Jpa does not throw any exception until the transaction will be commited or <code>EntityManager#flush()</code> will be invoked. </p>
  
  <p>I have two solutions. First is to add a flush() method to the UserRepository interface, and invoke <code>repository.flush()</code> after <code>repository.create(user)</code> in <code>UserServiceImpl#create</code> method. And second is invoke <code>entityManager.flush()</code> after <code>entityManager.persist(user)</code> in <code>JpaUserRepository#create</code> method and document it on the UserRepository interface.</p>
  
  <p>The First solution is not quite flexible because another implementation of UserRepository may not use an instruction cache but must implement flush() method. But as I know JpaRepository from Spring Data uses it. What approach will be best in this situation from the point view of flexibility?</p>