title: Spring Data Rest transaction boundaries
body: <p>I've been implementing some business logic/validation with the Spring Data Rest and JPA repositories using repository validators as described in: </p>
  
  <p><a href="http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events" rel="nofollow">http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events</a>.</p>
  
  <p>After digging deeper into the SDR code I noticed that the validators (or more generally, repository listeners) are not invoked within a transaction.</p>
  
  <p>From the source code of <code>org.springframework.data.rest.webmvc.RepositoryEntityController</code>:</p>
  
  <pre><code>private ResponseEntity&lt;ResourceSupport&gt; createAndReturn(Object domainObject, RepositoryInvoker invoker,
              PersistentEntityResourceAssembler assembler, boolean returnBody) {
          // validation logic is implemented in the listener, no transaction yet
          publisher.publishEvent(new BeforeCreateEvent(domainObject));
          // invoker calls repository, which is wrapped in the transactional proxy, 
          // only then transaction begins
          Object savedObject = invoker.invokeSave(domainObject);
          publisher.publishEvent(new AfterCreateEvent(savedObject));
  
          PersistentEntityResource resource = returnBody ? assembler.toFullResource(savedObject) : null;
  
          HttpHeaders headers = prepareHeaders(resource);
          addLocationHeader(headers, assembler, savedObject);
  
          return ControllerUtils.toResponseEntity(HttpStatus.CREATED, headers, resource);
  }
  </code></pre>
  
  <p>As seen in the code, the listeners are not called within a transaction, which could lead to eventual data consistency issues.</p>
  
  <p>Am I missing something? Or the framework simply sets the transactional boundary incorrectly?</p>