title: How to implement AuditorAware with Spring Data JPA and Spring Security?
body: <p>We use Hibernate/JPA, Spring, Spring Data and Spring Security in our application. I have a standard <code>User</code> entity which is mapped using JPA. Further, I have a <code>UserRepository</code></p>
  
  <pre><code>public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
      List&lt;User&gt; findByUsername(String username);
  }
  </code></pre>
  
  <p>which follows the Spring Data convention for naming query methods.  I have an entity </p>
  
  <pre><code>@Entity
  public class Foo extends AbstractAuditable&lt;User, Long&gt; {
      private String name;
  }
  </code></pre>
  
  <p>I want to use Spring Data auditing support. (As descripe <a href="http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/#jpa.auditing" rel="noreferrer">here</a>.) Hence I created a <code>AuditorService</code> as follows: </p>
  
  <pre><code>@Service
  public class AuditorService implements AuditorAware&lt;User&gt; {
  
      private UserRepository userRepository;
  
      @Override
      public User getCurrentAuditor() {
          String username = SecurityContextHolder.getContext().getAuthentication().getName();
          List&lt;User&gt; users = userRepository.findByUsername(username);
          if (users.size() &gt; 0) {
              return users.get(0);
          } else {
              throw new IllegalArgumentException();
          }
      }
  
      @Autowired
      public void setUserService(UserService userService) {
          this.userService = userService;
      }
  }
  </code></pre>
  
  <p>When I create a method</p>
  
  <pre><code>@Transactional
  public void createFoo() {
      Foo bar = new Foo(); 
      fooRepository.save(foo);
  }
  </code></pre>
  
  <p>Where everything is correctly wired and <code>FooRepository</code> is a Spring Data <code>CrudRepository</code>. Then a <code>StackOverflowError</code> is thrown since the the call to <code>findByUsername</code> seems to trigger hibernate to flush the data to the database which triggers <code>AuditingEntityListener</code> who calls <code>AuditorService#getCurrentAuditor</code> which again triggers a flush and so on. </p>
  
  <p>How to avoid this recursion? Is there a "canonical way" to load the <code>User</code> entity? Or is there a way to prevent Hibernate/JPA from flushing?    </p>