Limitation on the expressiveness of Hibernate (and JPA) Criteria?
I have 4 entities in a Hierarchy like this:
Parent
|
------------------------
| | |
Child1 Child2 Child3
And I am interested in retrieving All the instances of Child1 and Child2 (but not Child3 instances) with a criteria in a single Query.
This is easy to do with HQL (or JPQL) as follows:
FROM Parent obj
WHERE obj IN (FROM Child1 where fieldOfChild1="aa") OR
obj IN (FROM Child2 where fieldOfChild2=55)
I have studied the Hibernate Criteria and JPA Criteria APIs and I cannot find a way to express this query as a Criteria.
Is this a limitation of Criteria APIs? or is it开发者_开发技巧 just that I missed the way? Any hint?
If you have an discriminator value for each subclass in your mapping (eg. 1 for Child1, 2 for Child2, 3 for Child3) you can use the special attribute "class" in your HQL/Criteria.
So a criteria query could be like this:
session.createCriteria(Parent.class)
.add(Restrictions.or(Restrictions.eq("class", 1),
Restrictions.eq("class", 2)))
And your HQL query simplified:
FROM parent WHERE class = 1 OR class = 2
Well, you said that you haven't mapped your class hierarchy in your comment, have you?
So that a query for Child1 and Child2 can't be built with Criteria. In fact I don't think your HQL example works since Parent isn't mapped.
One ugly solution is to query to times, a Criteria query for Child1 and another Criteria query for Child2. And then merge both results lists in java code :( Or map the hierarchy :)
精彩评论