For example, i have two classes with parent - child relation: ParentClass, ChildClass
.
ParentClass
has ISet<ChildClass> Children
property.
Is it possible with single HQL to initialize all parent objects with its childrens.
views:
92answers:
1
+1
A:
It's possible using left join fetch clause in HQL:
select parent from ParentClass as parent
left join fetch parent.Children
where <whatever your conditions might be>
ChssPly76
2009-10-03 05:26:23
thx for reply,while trying do like you wrote, result items number always equals (Parents items*Children items), i mean for every child it create parent
ge1serf
2009-10-03 05:49:06
That shouldn't happen for a single parent / children association. Are you trying to fetch more than one collection at a time perhaps?
ChssPly76
2009-10-03 05:57:33
by now only one, may be something wrong with my mapping <set name="Children" table="Child" cascade="all" inverse="true"> <key column="ParentId"/> <one-to-many class="...Child, Namespace"/> </set>
ge1serf
2009-10-03 06:27:51
Your mapping looks fine. Does your Child map back to parent as many-to-one? So you're saying that the query as I wrote above (with conditions in where clause, if any, based strictly on parent) returns a cartesian product of parents and children? There must be something else involved if that's the case; you're not using Enumerable for that query by chance? Can you post both your mappings (Parent and Child) and your full query?
ChssPly76
2009-10-04 02:44:13
Child mapping:<many-to-one name="ParentId" class="Parent, Namespace"> <column name="ParentId" not-null="true" /></many-to-one>Query: select p from Parent p inner join fetch p... inner join fetch p... inner join fetch p.Children where ...Code in DAO: ArrayList parents = null; using (ISession s = HibernateTemplate.SessionFactory.OpenSession()) { IQuery q = s.GetNamedQuery("Parent.GetParent"); parents = q.List(); s.Close(); } return parents;}
ge1serf
2009-10-04 09:04:29
Why are you joining back to parent (with fetch no less) twice? That's what the problem is. Secondly, it's best using 'left join' rather than 'inner join' when you're retrieving collections (or nullable associations in general) because otherwise you won't get back parents that have ho children.
ChssPly76
2009-10-04 14:53:20