title: JPA - Spanning a transaction over multiple JpaRepository method calls
body: <p>I'm using SpringBoot 2.x with SpringData-JPA accessing the database via a CrudRepository.</p>
  
  <p>Basically, I would like to call the CrudRepository's methods to update or persist the data. In one use case, I would like to delete older entries from the database (for the brevity of this example assume: delete all entries from the table) before I insert a new element.
  In case persisting the new element fails for any reason, the delete operation shall be rolled back.</p>
  
  <p>However, the main problem seems to be that new transactions are opened for every method called from the CrudRepository. Even though, a transaction was opened by the method from the calling service. I couldn't get the repository methods to use the existing transaction.</p>
  
  <pre><code>Getting transaction for [org.example.jpatrans.ChairUpdaterService.updateChairs]
  Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.deleteWithinGivenTransaction]
  Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.deleteWithinGivenTransaction]
  </code></pre>
  
  <p>I've tried using different Propagation. (REQUIRED, SUPPORTED, MANDATORY) on different methods (service/repository) to no avail.
  Changing the methods <code>@Transactional</code> annoation to <code>@Transactional(propagation = Propagation.NESTED)</code> sounded that this would just do that, but didn't help.</p>
  
  <pre><code>JpaDialect does not support savepoints - check your JPA provider's capabilities
  </code></pre>
  
  <p>Can I achieve the expected behaviour, <strong>not</strong> using an EntityManager directly?<br>
  I also would like to avoid to having to be using native queries as well.
  Is there anything I have overlooked?</p>
  
  <p>For demonstration purposes, I've created a very condensed example.
  The complete example can be found at <a href="https://gitlab.com/cyc1ingsir/stackoverlow_jpa_transactions" rel="nofollow noreferrer">https://gitlab.com/cyc1ingsir/stackoverlow_jpa_transactions</a></p>
  
  <p>Here are the main (even more simplified) details:<br>
  First I've got a very simple entity defined:</p>
  
  <pre><code>@Entity
  @Table(name = "chair")
  @Data
  @AllArgsConstructor
  @NoArgsConstructor
  public class Chair {
  
    // Not auto generating the id is on purpose
    // for later testing with non unique keys
    @Id
    private int id;
  
    @Column(name = "legs", nullable = false)
    private Integer legs;
  }   
  </code></pre>
  
  <p>The connection to the database is made via the CrudRepository:</p>
  
  <pre><code>@Repository
  public interface ChairRepository extends CrudRepository&lt;Chair, Integer&gt; {
  }
  </code></pre>
  
  <p>This is being called from another bean (main methods here are <code>updateChairs</code> and <code>doUpdate</code>):</p>
  
  <pre><code>@Slf4j
  @Service
  @AllArgsConstructor
  @Transactional
  public class ChairUpdater {
  
      ChairRepository repository;
  
      /*
       * Initialize the data store with some
       * sample data
       */
      public void initializeChairs() {
  
          repository.deleteAll();
          Chair chair4 = new Chair(1, 4);
          Chair chair3 = new Chair(2, 3);
  
          repository.save(chair4);
          repository.save(chair3);
  
      }
  
      public void addChair(int id, Integer legCount) {
          repository.save(new Chair(id, legCount));
      }
  
      /*
       * Expected behaviour:
       * when saving a given chair fails -&gt;
       * deleting all other is rolled back
       */
      @Transactional        
      public void updateChairs(int id, Integer legCount) {
  
          Chair chair = new Chair(id, legCount);
          repository.deleteAll();
          repository.save(chair);
      }    
  }
  </code></pre>
  
  <p>The goal, I want to achieve is demonstrated by these two test cases:</p>
  
  <pre><code>@Slf4j
  @RunWith(SpringRunner.class)
  @DataJpaTest
  @Import(ChairUpdater.class)
  public class ChairUpdaterTest {
  
      private static final int COUNT_AFTER_ROLLBACK = 3;
      @Autowired
      private ChairUpdater updater;
  
      @Autowired
      private ChairRepository repository;
  
      @Before
      public void setup() {
          updater.initializeChairs();
      }
  
      @Test
      public void positiveTest() throws UpdatingException {
          updater.updateChairs(3, 10);
      }
  
      @Test
      public void testRollingBack() {
  
          // Trying to update with an invalid element
          // to force rollback
          try {
              updater.updateChairs(3, null);
          } catch (Exception e) {
              LOGGER.info("Rolled back?", e);
          }
  
          // Adding a valid element after the rollback
          // should succeed
          updater.addChair(4, 10);
          assertEquals(COUNT_AFTER_ROLLBACK, repository.findAll().spliterator().getExactSizeIfKnown());
      }
  }
  </code></pre>
  
  <p>Update:</p>
  
  <p>It seems to work, if the repository is not extended from either CrudRepository or JpaRepository but from a plain Repository, definening all needed methods explicitly. For me, that seems to be a workaround rather than beeing a propper solution.<br>
  The question it boils down to seems to be: Is it possible to prevent SimpleJpaRepository from opening new transactions for every (predefined) method used from the repository interface? Or, if that is not possible, how to "force" the transaction manager to reuse the transaction, opened in the service to make a complete rollback possible?</p>