Hibernate Criteria Filtering by attributes of collection

I am using the criteria sub API of hibernate for managing dynamic queries that a front user can perform. As long the filtering is done thought properties of the root entity (called it "Root") everything is fine, assuming that the associations paths are properly specified with alias.

But i reach a complicated query to perform, it involves a collection of child objects (whose class let's call it "Child"). I have to select root entities not only by the value of a property of child object (that is can be done very trivial), a have to go deeper and also check, for that child object (that fulfill some criteria) if matches another criteria, but only for that child!

So, putting it on more concrete examples, let's assume the following declarations:

class Root {
    Long id;
    Collection<Child> childs;
}

class Child {
    Long id;
    ValueObject attr;
}

class ValueObject {
    String attribute;
}

And when the times to perform the query comes, this is the code that a fortune thread executes :

Criteria criteria = session.createCriteria(Root.class);
criteria.createAlias("childs","childs");
criteria.createAlias("childs.attr","attr_childs");
criteria.add(Restrictions.eq("childs.id",20L));
criteria.add(Restrictions.eq("childs.attr","foo"));

But i want, not to matches all the Root objects that contains a child whose id is 20 and, on the other hands, that also contains another child (doesn't matter if it is the same) whose attr value is "foo". What i really want is to retrieve all the Root object that contains a child whose id is 20 and whose attr value is "foo", (all of this restrictions are fulfilled by the same entity child!).

I try to find information about this, but all seems to obfuscated!

If someone could help i will be very grateful!

Thanks to all!

Greetings!

Víctor.

链接地址: http://www.djcxy.com/p/6324.html

上一篇: Hibernate标准对子集合有多个限制

下一篇: Hibernate Criteria按集合的属性过滤