Hibernate HQL: using JOIN to eagerly load child entities?
I found this HQL query that I am trying to make sense of. The comment says the LEFT JOIN
causes Hibernate to eagerly load the associated entities in the child table, and the DISTINCT
modifier is needed to filter out duplicate parent entities in the result set. Do these comments make sense? I have not seen a join used this way before.
SELECT DISTINCT p FROM Parent AS p
LEFT JOIN p.children AS c
WHERE p.state = 1
ORDER BY p.modified
Note c
is not used in the WHERE
or ORDER BY
clauses.
It seems it would be safe to replace this query with the simpler:
SELECT p FROM Parent AS p
WHERE p.state = 1
ORDER BY p.modified
But I am not sure if there is a good reason the original query was written as i开发者_如何转开发s.
According to Hibernate documentation:
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html
So it's only the "fetch" join that causes the referred collections to load. In your case, you don't have a "fetch" join, so I don't think the collection of children will be loaded via this query.
In other words, yes, you could replace the query with the second one.
精彩评论