title: Spring @Transactional and concurrency
body: <p>I have a Spring controller with the following method: </p>
  
  <pre><code>    @PostMapping("/tables")
      @Transactional(isolation = Isolation.SERIALIZABLE)
      public ResponseEntity&lt;Table&gt; addTable(@RequestBody Table table) {
          if (table.getTableNumber() == 0) {
              table.setTableNumber(tableRepository.count() + 1);
          }
          return new ResponseEntity&lt;&gt;(tableRepository.save(table), HttpStatus.CREATED);
      }
  </code></pre>
  
  <p>I would like multiple invocations to happen sequentially, so that at every invocation the <code>count</code> method will return the correct number of rows (at the moment it doesn't happen, because multiple invocations can run concurrently).</p>
  
  <p>I tried to figure out the best way to do so, and I came to these conclusions (please correct me if I'm wrong): </p>
  
  <ol>
  <li>Using <code>@Transactional</code> doesn't help, as multiple transactions can still run concurrently</li>
  <li>Anyway, <code>@Transactional</code> will prevent a complex method to persist only a portion of the data when <code>save</code> is called multiple times (this isn't the case)</li>
  <li><code>isolation = Isolation.SERIALIZABLE</code> only determines how the new transaction relates to the ones that already finished (in this case, the new transaction would see the DB in its newest form)</li>
  </ol>
  
  <p>I read that I could use a lock with <code>@Lock</code> to have exclusive access to a table, but I only saw it applied to single methods (like <code>findById</code>), while in my case the lock would have to span multiple operations (the <code>count</code> and the <code>save</code>). Is there a way to lock a table arbitrarily (either using annotations or programmatically)? Locking an entire table may seem a bit drastic, but at least methods operating on different tables could still run concurrently (this cannot be achieved just by using <code>synchronized</code> at the method level, while it would be possible by locking on the repositories, but it definitely doesn't seem a clean job). </p>
  
  <p>It sounds strange that Spring doesn't offer a simple way to say "ehi, I want this method operating on this repository to run only from a thread at once". Am I missing something? </p>