title: How to LOCK TABLE ... do stuff ... UNLOCK TABLE with Spring Boot?
body: <p>The idea is basically to extend <em>some</em> Repositories with custom functionality. So I got this setup, which DOES work!</p>
  
  <pre class="lang-java prettyprint-override"><code>@MappedSuperclass
  abstract class MyBaseEntity {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      var id: Int = 0
  
      var eid: Int = 0
  
  }
  
  interface MyRepository&lt;T : MyBaseEntity&gt; {
  
      @Transactional
      fun saveInsert(entity: T): Optional&lt;T&gt;
  }
  
  open class MyRepositoryImpl&lt;T : MyBaseEntity&gt; : MyRepository&lt;T&gt; {
  
      @Autowired
      private lateinit var entityManager: EntityManager
  
      @Transactional
      override fun saveInsert(entity: T): Optional&lt;T&gt; {
  
          // lock table
          entityManager.createNativeQuery("LOCK TABLE myTable WRITE").executeUpdate()
  
          // get current max EID
          val result = entityManager.createNativeQuery("SELECT MAX(eid) FROM myTable LIMIT 1").singleResult as? Int ?: 0
  
          // set entities EID with incremented result
          entity.eid = result + 1
  
          // test if table is locked. sending manually 2-3 POST requests to REST
          Thread.sleep(5000)
  
          // save
          entityManager.persist(entity)
  
          // unlock
          entityManager.createNativeQuery("UNLOCK TABLES").executeUpdate()
  
          return Optional.of(entity)
      }
  }
  </code></pre>
  
  <p><strong>How would I do this more spring-Like?</strong> </p>
  
  <p>At first, I thought the <code>@Transactional</code> would do the LOCK and UNLOCK stuff. I tried a couple of additional parameters and <code>@Lock</code>. I did go through docs and some tutorials but the abstract technical English is often not easy to understand. At the end, I did not get a working solution so I manually added the table-locking, which works fine. Still would prefer a more spring-like way to do it.</p>