title: Spring JPA Transaction
body: <p>I am encountering some strange behavior in Spring managed transactions. This a Spring MVC app. I am binding entities directly to the Web tier. I load a persistent entity from the database for edit using the following service layer code which is called from a method annotated with @ModelAttribute. </p>
  
  <pre><code>@Transactional(readOnly = true)
  @PreAuthorize("#id == authentication.principal.id or hasRole('ROLE_ADMIN')")
  public User findById(Long id) {
      return repository.findOne(id);
  }
  </code></pre>
  
  <p>When the form is submitted the data is bound to this detached entity. As part of validation I query the database to validate that the email address specified for the User is unique.</p>
  
  <pre><code>@Transactional(readOnly = true)
  public boolean isEmailAddressUnique(String emailAddress, Long userId){
      return repository.checkEmailAddressUnique(emailAddress, userId) == 0;
  }
  </code></pre>
  
  <p>At this point, before executing this query, Hibernate attempts to flush the previously loaded detached entity which I don't understand. Obviously this results in an Exception if the email address is not unique.</p>
  
  <p>I am using the OpenEntityManagerinViewFilter however I would expect that this should have FlushMode set to NEVER, perhaps not.</p>
  
  <p>If I remove the @Transactional attribute from the isEmailAddressUnique() the flush does not occur and verything works as expected which I suppose solves the issue however I would like to understand what is going on here.</p>
  
  <p>Any suggestions?</p>
  
  <p>=============</p>
  
  <p>Okay, I have investigated further. So I have OpenEntityManagerInViewFilter configured with defaults:</p>
  
  <p>Scenario One.</p>
  
  <p>[1] MVC Controller loads A User entity in a readOnly transaction T1
  [2] Entity is modified as a result of MVC field binding
  [3] Second transaction runs against Users table in a readOnly transaction T2.
  [4] Hibernate flushes the entity loaded in T1.
  [5] Hibernate issues the query</p>
  
  <p>Scenario 2.</p>
  
  <p>Subclassed the OEMIVFilter to set the FlushMode to commit (default is auto).</p>
  
  <p>As above with steps [4] and [5] reversed, viz. even though T2 is marked as readOnly Hibernate still attempts to Flush at the end of the transaction. I could understand scenario 1 as readOnly may only refer to the current transaction T2 (and will attempt to synchronize the database before executing T2). However I would expect that in scenario 2 no Flush should be issued.</p>