schmmd
schmmd

Reputation: 19468

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 unnecessary. Is there a neater way to fetch both bar and baz?

Upvotes: 2

Views: 856

Answers (1)

Speck
Speck

Reputation: 2299

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

Upvotes: 1

Related Questions