Video in progress
The application's memory grows slowly, and in the heap dump Hibernate's query plan cache takes a lot of space. How do IN (:ids) queries cause this?
Every different length of the IN list is a separate SQL string for Hibernate and a separate entry in the cache: ids from 1 to 1000 mean 1000 different queries. hibernate.query.in_clause_parameter_padding=true rounds lengths up to powers of 2 and cuts the variants sharply; very long lists need a different approach.
📖 Answer
@Query("select p from Product p where p.id in :ids")
List<Product> findAllByIds(@Param("ids") Collection<Long> ids);
There is one JPQL, but when it is turned into SQL a separate ? is put in for each element: in (?), in (?,?), in (?,?,?)... Every length is a new SQL text, a new cache entry, and in the database a separate prepared statement and plan too.
Hibernate's cache is bounded (hibernate.query.plan_cache_max_size), so it doesn't grow forever. But thousands of variants of complex queries can take hundreds of megabytes, and because the cache is constantly full and churning, its benefit disappears too.
The first, cheapest fix:
spring.jpa.properties.hibernate.query.in_clause_parameter_padding: true
Now 5 ids become in (?,?,?,?,?,?,?,?): the last value is repeated. For lengths 1..1000 about 11 variants remain.
Next steps:
- if the list is very long, split it into batches: Oracle limits
INto 1000 elements, and JDBC drivers also cap the number of parameters in one query; - in PostgreSQL, send an array as a single parameter: native
where id = any(:ids). The SQL text is always the same; - for tens of thousands of ids, a temporary table and a
join.
Diagnostics: getQueryPlanCacheHitCount() and getQueryPlanCacheMissCount() in Hibernate statistics. If there are a lot of misses, you have many dynamic SQL variants. The same problem shows up in Criteria queries that are built in different shapes depending on user filters.
Sign up to mark studied questions and save your progress.