How can you query for an object using one of its properties' id
- by James Smith
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?