Video in progress

Strong Middle 🐻 Hibernate and JPA

In Hibernate 6, do you still need `select distinct` when you `join fetch` a collection?

To remove duplicates of the root entity, not anymore: Hibernate 6 does it itself. In Hibernate 5, distinct went into the SQL and also deduplicated in Java, so it was common to remove it from the SQL with the QueryHints.PASS_DISTINCT_THROUGH=false hint.

📖 Answer

In Hibernate 5:

select p from Post p join fetch p.comments

A post with 3 comments would appear 3 times in the result list: one reference per JOIN row. That's why you wrote select distinct p. But this DISTINCT also went into the SQL, and the database would compare all the columns to sort them, even though the rows were different anyway (the comment columns differ). That's wasted work, and people turned it off with the hibernate.query.passDistinctThrough=false hint.

In Hibernate 6:

  • root entities obtained with a fetch join appear exactly once in the result list automatically;
  • distinct still works if you write it, but it goes into the SQL as DISTINCT;
  • the passDistinctThrough hint was removed.

So in 6, don't write distinct for a fetch join: it only makes the SQL heavier. For scalar queries (select distinct c.city from Customer c), of course, you still need it as before.

During migrations I often see this: in the old code distinct was left on every fetch join, and after the move to 6 the queries slowed down on big tables. In the EXPLAIN you see an extra HashAggregate or Unique step, and this is the reason.