In a database with tables contact and address I would like to find the housemates of a given contact.
The following HQL query is a good start:
SELECT DISTINCT con FROM Contact con JOIN FETCH con.address add LEFT JOIN FETCH add.relations mate
That is, it yields a collection of contacts, each of which has a single address, each of which has a collection of all contacts living at that address. As expected, each contact lists itself as housemate, which is not what I want. Let’s try a refinement:
SELECT DISTINCT con FROM Contact con JOIN FETCH con.address add LEFT JOIN FETCH add.relations mate WHERE con.id<>mate.id
Here, the ‘where’ clause is ignored, as per the Hibernate documentation (Section 14.3):
A fetch join does not usually need to assign an alias, because the associated objects should not be used in the
whereclause (or any other clause). The associated objects are also not returned directly in the query results. Instead, they may be accessed via the parent object. The only reason you might need an alias is if you are recursively join fetching a further collection
The generated SQL works as expected, though.
Is there any way to get this to work, other than by manually populating the housemates collection?