Search code examples
spring-data-jpatransactions

What is the relation between a thread and transaction in JPA?


I am aware that JPA works with the default isolation level set for the database , if no isolation level is explicitly specified using the @Transactional annotation. So, for a simple JPA query like findByID(someId), is the transaction limited to the JPA query, or the transaction is applicable throughout the request thread ?

If I execute findById() method twice in the same thread, does it execute within the same transaction ?


Solution

  • If you don't specify transaction boundaries with annotations or programmatic transactions then each query executes in its own transaction.

    JPA flushes before the transaction commits, so each findById will make its own database query, then flush the cached results. So if you call findById twice it will result in two queries.

    You can verify this by viewing logging of transactions, see Showing a Spring Transaction in log.

    Isolation level is a different issue from transaction boundaries. Most transaction properties (the A, C, and D in ACID) are all-or-nothing, but isolation isn't, it can be dialed up or down. Isolation level determines how changes in one transaction become visible to other transactions in progress.