tags:

views:

22

answers:

1

I have two entities, say, House and People, where multiple people can live in one house.

It's a unidirectional link where each Person has a field for which House they belong to, so the Person table has a column named house_id.

I need to be able to return all the Person objects who belong to a certain House, but I only have the id of the house.

This can be done like this:

House house = houseDAO.findById(houseId);
List people = session.createCriteria(Person.class).add(Restrictions.eq("house", house)).list();

But since I don't need the house, that's adding an unnecessary query. I've tried to do:

session.createCriteria(Person.class).add(Restrictions.eq("house_id", houseId)).list();

But that doesn't work because house_id is not a property, it's a database column. I could just add an sql restriction, but is there a hibernate way of doing this?

+1  A: 

It's always easy to forget you're working with HQL, not SQL. I do it all the time. When using HQL, you want to refer to fields of the class you're dealing with, not the column names.

session.createCriteria(Person.class).add(Restrictions.eq("house.id", houseId)).list();
unsquared