Video in progress

Strong Middle 🐻 Hibernate and JPA

Does Hibernate grab the connection as soon as a transaction starts, and what is the `provider_disables_autocommit` setting for?

Spring's JpaTransactionManager takes a connection at the start of the transaction and turns autoCommit off, even if the first SQL statement is still a long way off. If the pool already hands out connections with autoCommit=false, hibernate.connection.provider_disables_autocommit=true tells Hibernate so, which lets it delay acquiring the connection until the first query.

📖 Answer

The usual flow: you enter a @Transactional method, Spring starts the Hibernate transaction, and Hibernate takes a connection from the pool, checks the autoCommit state and calls setAutoCommit(false). After that the connection stays busy even if the method then waits 300 ms for an external service.

Under load this is noticeable: with a 20-connection pool, the time each transaction holds a connection for nothing at the start directly lengthens the pending queue.

The configuration:

spring:
  datasource:
    hikari:
      auto-commit: false
  jpa:
    properties:
      hibernate.connection.provider_disables_autocommit: true

Now Hibernate doesn't have to take a connection just to check autoCommit. In a resource-local transaction it takes the connection when the first real SQL is needed. With Spring's JpaTransactionManager the benefit depends on the version: in some configurations Spring opens the JDBC connection up front anyway (for example, to synchronize with DataSourceUtils). So measure the result in the Hikari metrics (hikaricp.connections.usage).

There's one risk, but a serious one: if you set auto-commit: false and then write code without a transaction (for example, an UPDATE with JdbcTemplate and no @Transactional), the change isn't committed and gets rolled back when the connection returns to the pool. Before turning this setting on, I check that all the write paths are inside a transaction.

The biggest win is still elsewhere, though: moving external HTTP calls out of the transaction.