开发者

Querying a hibernate entity with two one-to-many collections

I am selecting a number (x) of entities Foo using Hibernate. Each foo has one-to-many collections bar and baz that are set to lazy fetching. I will need to populate bar and baz for each foo, so I definitely do not want a subselect to be issued per collection (2 * x + 1 selects).

However, I also don't necessarily want to setFetchMode(FetchMode.JOIN) on both because this will return the Cartesian product (bar x baz). Also, if I define foo and bar as Lists, I will receive duplicate items. I can issue two Criterias:

List<Foo> foos;
foo = session.createCriteria(Foo.class).setFetchMode("bar", FetchMode.JOIN).list();
foo = session.createCriteria(Foo.class).setFetchMode("baz", FetchMode.JOIN).list();

but the code looks rather sloppy. It looks like the first query was unne开发者_StackOverflow中文版cessary. Is there a neater way to fetch both bar and baz?


I'd dump the criteria and use HQL for this.

String hql = "select new list(foo.bar, foo.baz) from Foo foo";
Query query = session.createQuery(hql);
List list = query.list;
Bar bar = list.get(0);
Baz baz = list.get(1);

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜