title: jpa flush or find before persist
body: <p>In Spring declarative transactions management, when you trying to persist some entity which already exists in database, you are getting DataIntegrityViolationException only during Spring transaction commits. Therefore this method wouldn't work, exception in <code>catch</code> braces wouldn't caught here: </p>
  
  <pre><code>@Repository
  public class UserDAOImpl implements UserDAO {
  
      @PersistenceContext
      EntityManager em;
  
      @Override
          public void createUserRole(String role) throws RoleAlreadyExistsException {
              try {
                  UserRole userRole = new UserRole(role);
                  em.persist(userRole);
              } catch (Exception e) {
                  throw new RoleAlreadyExistsException();
              }
          }
  }
  </code></pre>
  
  <p>only in the end of: </p>
  
  <pre><code>@Service("userService")
  public class UserService 
      @Transactional
          public void createUserRole(String role) throws RoleAlreadyExistsException {
              userDao.createUserRole(role);
          }
  }
  </code></pre>
  
  <p>I found out few options to resolve it:</p>
  
  <ul>
  <li>not use @Transaction</li>
  <li>use Flush</li>
  <li>catch exception when invoke service</li>
  <li>look up before persist</li>
  </ul>
  
  <p>And now I considering between em.flush and em.find (before persist). Which  method would be better to use(flush - losing performance, find - redundant request to database)? Also if i mistake somewhere here please point me.</p>