views:

1121

answers:

2

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?

+1  A: 

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.

laz
A: 

You can use Criteria or HQL.

HQL example:

Query query = session.createQuery("from Bar as bar where bar.aMember.id = :fooId");

query.setParameter("fooId", fooId);

List result = query.list();

Theine