Search code examples
hibernatecriteria-apiquarkus-panachemutiny

How to avoid duplicate entities on lazy associations fetch with Criteria API?


When performing a join fetch to load lazy associations with a Hibernate 5 query, the returned result list may contain duplicate entities. Hibernate supports hints such as HINT_PASS_DISTINCT_THROUGH in order to avoid the use of DISTINCT in the resulting SQL query and efficiently filter out duplicates in the result list.

What is the best practice way of eliminating such duplicates when using JPA Criteria API?

Note the following:


Solution

  • javax.persistence.Query#setHint or javax.persistence.TypedQuery#setHint seem to be the most commonly used methods to provide hints of this kind with Criteria API.

    Session session = HibernateUtil.getHibernateSession();
    CriteriaBuilder cBuilder = session.getCriteriaBuilder();
    CriteriaQuery<Example> cQuery = cBuilder.createQuery(Example.class);
    ...
    cQuery.distinct(true);
    ...
    Query<Example> query = session.createQuery(cQuery);
    query.setHint("HINT_PASS_DISTINCT_THROUGH", false);
    return query.getResultList();