Video in progress

Strong Middle 🐻 Hibernate and JPA

What is Hibernate's `StatementInspector`, and what practical purposes do you use it for?

StatementInspector is a hook Hibernate calls before sending each SQL statement to JDBC: it receives the SQL string and returns a (modified) string. I use it to add a trace id or endpoint name to a query as a comment, to count queries in tests, and to catch dangerous SQL. Not for changing the meaning of the SQL.

📖 Answer

public class TraceCommentInspector implements StatementInspector {
    @Override
    public String inspect(String sql) {
        String trace = MDC.get("traceId");
        return trace == null ? sql : "/* trace=" + trace + " */ " + sql;
    }
}
spring:
  jpa:
    properties:
      hibernate.session_factory.statement_inspector: com.shop.db.TraceCommentInspector

Now when you see a slow query in PostgreSQL's pg_stat_activity or the slow query log, you can find right away which HTTP request it came from, by trace id. It's very handy when talking to a DBA.

Other useful uses:

  • counting queries in tests: a ThreadLocal counter in the inspector, and at the end of the test assertThat(count).isLessThanOrEqualTo(3);
  • catching queries with no where, like select ... from orders, with a warning in the dev environment;
  • writing a particular query to the log for temporary diagnostics.

Things to watch out for:

  • the inspector is called for every SQL statement, so don't do heavy work in it;
  • every different value in the comment changes the SQL text. On some databases (Oracle, for example) this can break the statement cache. On PostgreSQL pg_stat_statements strips comments during normalization, but the JDBC prepared statement cache still stores each different text separately, so putting the endpoint name in the comment rather than a unique trace id is often safer;
  • don't use it to "fix" SQL (adding conditions, swapping tables). That's invisible magic that's hard to understand and maintain. If you need a tenant filter, there's @TenantId or @Filter.