Hibernate Query for a List of Objects that matches a List of Objects' ids

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?

Answers


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.


Need Your Help

Convert codes to HTML with CSS style

vim

I normally use VIM to edit my codes and convert them to HTML by using TOhtml command. The only thing I don't like is that the converted HTML does not have css class style definitions. I am not sure...

AngularJS blocks submit button in symfony2 form

javascript php angularjs symfony

I have form created in symfony2, which at the end renders button to submit form. When I add ng-app="myApp" everything works fine, but I can't submit form which is on this page. Why is that and how to