开发者

Hibernate projection on many-to-many property

I'm using Hibernate 3.3.2. I have class A, which has a property b, which maps a many-to-many relation to B.

Class A has the following mapping:

<set name="b" table="a_b" lazy="true">
   <key column="id_a"/>
   <many-to-many class="B" column="id_b" outer-join="auto" />
</set>

I am trying the following:

Criteria c = HibernateUtil.getSession().createCriteria(A.class);
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("id_a"), "id_a");
pl.add(Projections.property("b"), "b");
c.s开发者_C百科etProjection(pl);
c.add(Restrictions.eq("id", id));
Object o = c.list();

This code doesn't load any instance of B; the element corresponding to b in the returned ArrayList is null. Do you have any idea?

Thanks.


The code you provided fetchs the list of B entity of a specific A row. You should do the join in the inverse way, fetch B and join A just to restrict the query:

Criteria c = HibernateUtil.getSession().createCriteria(B.class);
c.createCriteria("a").add(Restrictions.eq("id", id));
List<B> o = (List<B>) c.list();

The above code should do the trick.


Since fetchType is lazy you need to create an alias for b: c.createAlias(...) so that hibernate will join A with B.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜