Hibernate — load an object based on a member object’s field

criteriahibernate

How can an object be loaded via Hibernate based on a field value of a member object? For example, suppose the following classes existed, with a one-to-one relationship between bar and foo:

Foo {
    Long id;
}

Bar {
    Long id;
    Foo aMember;
}

How could one use Hibernate Criteria to load Bar if you only had the id of Foo?

The first thing that leapt into my head was to load the Foo object and set that as a Criterion to load the Bar object, but that seems wasteful. Is there an effective way to do this with Criteria, or is HQL the way this should be handled?

Best Solution

You can absolutely use Criteria in an efficient manner to accomplish this:

session.createCriteria(Bar.class).
        createAlias("aMember", "a").
        add(Restrictions.eq("a.id", fooId));

ought to do the trick.