views:

64

answers:

1

Given a classes Foo, Bar which have hibernate mappings to tables Foo, A, B and C

public class Foo {
  Integer aid;
  Integer bid;
  Integer cid;
  ...;
}

public class Bar {
  A a; 
  B b; 
  C c; 
  ...;
}

I build a List fooList of an arbitrary size and I would like to use hibernate to fetch List where the resulting list will look something like this:

Bar[1] = [X1,Y2,ZA,...]
Bar[2] = [X1,Y2,ZB,...]
Bar[3] = [X1,Y2,ZC,...]
Bar[4] = [X1,Y3,ZD,...]
Bar[5] = [X2,Y4,ZE,...]
Bar[6] = [X2,Y4,ZF,...]
Bar[7] = [X2,Y5,ZG,...]
Bar[8] = ...

Where each Xi, Yi and Zi represents a unique object.

I know I can iterate fooList and fetch each List and call barList.addAll(...) to build the result list with something like this:

List<bar> barList.addAll(s.createQuery("from Bar bar where bar.aid = :aid and ... ")
    .setEntity("aid", foo.getAid())
    .setEntity("bid", foo.getBid())
    .setEntity("cid", foo.getCid())
    .list();
    );

Is there any easier way, ideally one that makes better use of hibernate and make a minimal number of database calls?

Am I missing something? Is hibernate not the right tool for this?

A: 

Turns out that the following did what I wanted:

  • Define a component Foo in the hibernate class mapping Bar with the properties needed to select the items
  • Mapping should link the complex types to the ids via one-to-one mappings
  • Populate a List of Foo objects with ids that will select a list of Bars

A list of Bar can be fetched via

List<Foo> lf = this.getTheListOfFooWithIds(...);
Query qb = session.createQuery("from Bar b where b.foo in (:foo)");
qb.setParameterList("foo", lf);
List l = qb.list();

This got me what I needed.

The SQL created by hibernate was not as awful as I expected.

sal