Search code examples
hibernatejoinduplicateshqlfetch

HQL returns duplicate objects


I have two questions regarding HQL usage

  1. I have a query like below, but it returns duplicate rows/objects, adding DISTINCT keyword solves the problem but can someone explain, why we need distinct here, can't we do without it?

    select st from State st inner join fetch st.cities
    
  2. The HQL documentation says that

    A fetch join does not usually need to assign an alias, because the associated objects should not be used in the where clause (or any other clause).

    but why can't we use the associated objects in the where clause, if we want to eagerly fetch but also want to add some condition then how to do it?


Solution

    1. Simply because that's how HQL and JPQL are specified: one element is returned per row of the JDBC ResultSet, unless you use distinct.

    2. Because if you were allowed to add restrictions on the fetched entities, you would break the invariants of your entities themselves, that Hibernate, and your own code, assume to be always verified: the cities returned by state.getCities() are the cities of the state. All of them. Not just the ones that happen to obey some criteria of a random query.