[英]Hibernate: Criteria Query child objects (associations) by Entity (not Id)
I would like to query a Parent object by a list of child objects with Hibernate Criteria Query. 我想通过Hibernate Criteria Query通过子对象列表来查询Parent对象。 I know how to do it with IDs of the childs but not using entities directly.
我知道如何使用孩子的ID,但不直接使用实体。
This works: 这有效:
List<Long> listOfChildLongChildIds = new ArrayList<Long>();
listOfChildLongChildIds.add(new Long(1));
listOfChildLongChildIds.add(new Long(2));
Criteria criteria = getSession().createCriteria(Parent.class);
Criteria criteriaChilds = criteria.createCriteria("childs");
criteriaChilds.add(Restrictions.in("id", listOfChildLongChildIds));
But how to do this, when the list contains Child Objects/Entities like this: 但是,当列表包含以下子对象/实体时,该如何做:
List<Child> listOfChildEntities = new ArrayList<Child>();
listOfChildEntities.add(QueryChildFromDatabse);
listOfChildEntities.add(QueryChildFromDatabse);
(This means I do not use the ID of the child but only the Entitiy itself. The reason is otherwise I would have to iterate through my list of childs and extract all Ids and put them into a list what I think is most likely unnecessary. But I was not able to find any information how to query by entity lists itself): (这意味着我不使用孩子的ID,而仅使用实体本身。原因是否则,我将不得不遍历我的孩子列表并提取所有ID,然后将它们放入列表中,这是我认为最可能不必要的。但是我找不到任何信息,如何通过实体列表本身进行查询):
Then the code above using 然后上面的代码使用
criteriaChilds.add(Restrictions.in("id",listOfChildEntities));
will throw an exception: 会抛出异常:
Child cannot be cast to java.lang.Long
子级不能转换为java.lang.Long
I think you should be able to do something like: 我认为您应该可以执行以下操作:
Criteria criteria = getSession().createCriteria(Parent.class);
criteria.createCriteria("childs","childs");
criteria.add(Restrictions.in("childs.id", listOfChildLongChildIds));
您应该能够将对象传递给Restrictions.in方法。
Restrictions.in("childs", <childObjectslist>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.