Video in progress

Strong Middle 🐻 Hibernate and JPA

What happens if you pass 100 thousand ids to a `where id in (:ids)` query, and how do you write it in that case?

Each id becomes a separate bind parameter. On the PostgreSQL JDBC driver you hit the parameter count limit (roughly 32-65 thousand, depending on the driver) and it fails, and on Oracle an IN list can't exceed 1000 elements. On top of that, the plan cache bloats. The fix is to split into batches, use an array parameter (= any(?)) on PostgreSQL, or join against a temporary table.

📖 Answer

List<Order> list = em.createQuery("select o from Order o where o.id in :ids", Order.class)
    .setParameter("ids", ids)       // 100,000 of them
    .getResultList();

Hibernate turns this into in (?, ?, ?, ... ). The consequences:

  • PostgreSQL driver: Tried to send an out-of-range integer as a 2-byte value or a similar error, since the protocol limits the number of parameters;
  • Oracle: ORA-01795: maximum number of expressions in a list is 1000;
  • even if you don't hit the limit, each different length means a new SQL text, a new entry in Hibernate's plan cache and the database's statement cache. hibernate.query.in_clause_parameter_padding=true softens this;
  • parsing SQL with 100 thousand parameters is slow in itself.

Loading in batches is the simplest and most portable way:

List<Order> result = new ArrayList<>();
for (List<Long> chunk : ListUtils.partition(ids, 1000)) {
    result.addAll(repo.findAllById(chunk));
}

An array parameter on PostgreSQL:

em.createNativeQuery("select * from orders where id = any(cast(:ids as bigint[]))", Order.class)
  .setParameter("ids", ids.toArray(Long[]::new))
  .getResultList();

One parameter, one SQL text, any length.

But first ask the question: where do these 100 thousand ids come from? Often they're the result of another query, and then merging the two queries into a single join or subquery beats everything else. If the ids come from outside (a file, another service), the most stable way is to COPY them into a temporary table and join.