views:

336

answers:

2

I have a problem in creating subqueries with Hibernate. Unfortunately the Subqueries class is almost entirely undocumented, so I have absolutely no clue how to convert the following SQL into a Hibernate Criteria:

SELECT id
FROM car_parts
WHERE car_id IN ( SELECT id FROM cars WHERE owner_id = 123 )

I was hoping the following would 'just work':

session.createCriteria(CarParts.class).add(eq("car.owner", myCarOwner));

but unfortunately it does not. So it seems I actually have to use the Subqueries class to create the Criteria. But I was unable to find a reasonable example though Google, so that leads me to asking it here.

+2  A: 

Try to create an alias for the "car" property before adding the eq expression like this:

session.createCriteria(CarParts.class)  
        .createAlias("car", "c")  
        .add(eq("c.owner", myCarOwner));
Tom van Zummeren
A: 

As first check the ORM configuration between Car and CarPart entities, usually you need the setup the relationship between them. After that try to execute the following code:

List result = session.createQuery("from " + CarPart.class.getName() + " as parts join parts.car as car where car.owner = :myOwner").setParameter("myOwner", 123).list();