Video in progress

Strong Middle 🐻 Hibernate and JPA

If you need raw JDBC inside a Hibernate session (`Session.doWork`), what do you watch out for with the transaction and flush?

doWork hands you the same connection Hibernate is using, so the work runs in that same transaction. But Hibernate doesn't know about the SQL you write: you need to flush() before it, and afterward the entities in the context may be stale. Don't close the connection and don't change auto-commit.

📖 Answer

The usual reason is that you need something JPA doesn't have: PostgreSQL COPY, a custom setFetchSize, a driver-specific API.

@Transactional
public void bulkLoad(Path csv) {
    em.flush();   // pending Hibernate INSERTs/UPDATEs go to the database first
    Session session = em.unwrap(Session.class);
    session.doWork(conn -> {
        CopyManager copy = conn.unwrap(PGConnection.class).getCopyAPI();
        try (Reader r = Files.newBufferedReader(csv)) {
            copy.copyIn("copy price_import(sku, price) from stdin with (format csv)", r);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
    em.clear();   // the data in the context may now be stale
}

Things to watch:

  • flush(): otherwise the rows you write through JDBC depend on rows Hibernate hasn't sent yet (a parent record behind an FK, for example) and fail;
  • don't close() the connection and don't touch setAutoCommit(): it belongs to the Spring/Hibernate transaction;
  • the L2 cache doesn't know about these changes. Evict the relevant region yourself (emf.getCache().evict(Price.class));
  • if you need to return a result, there's doReturningWork.

An alternative in Spring is to use JdbcTemplate inside the same @Transactional: JpaTransactionManager binds the JDBC connection to the transaction too, so it also works in that same transaction. The flush rule applies here as well: JdbcTemplate doesn't flush Hibernate automatically.