How can you query for an object using one of its properties' id
Posted
by James Smith
on Stack Overflow
See other posts from Stack Overflow
or by James Smith
Published on 2010-06-10T15:48:21Z
Indexed on
2010/06/10
15:53 UTC
Read the original article
Hit count: 280
hibernate
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?
© Stack Overflow or respective owner