java Hibernate 条件查询不同对象的不同属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1528352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate criteria query on different properties of different objects
提问by RMorrisey
Suppose I have classes like:
假设我有这样的课程:
class A {
B getB();
C getC();
}
class B {
String getFoo();
}
class C {
int getBar();
}
and I want to filter criteria on A, two filters on different subclass properties, like:
我想在 A 上过滤条件,两个过滤器在不同的子类属性上,例如:
Criteria criteriaA = session.createCriteria(A.class);
Criteria criteriaB = criteriaA.createCriteria("b").add(Restrictions.eq("foo", "Something"));
Criteria criteriaC = criteriaA.createCriteria("c").add(Restrictions.eq("bar", 0));
What I want to do is combine criteriaB and criteriaC using an "or" clause, something like:
我想要做的是使用“或”子句组合criteriaB和criteriaC,例如:
//this does not work
criteriaA.add(Restrictions.disjunction().add(criteriaB).add(criteriaC));
How can I accomplish this? I am stumbling a little over the API here.
我怎样才能做到这一点?我对这里的 API 有点磕磕绊绊。
回答by ChssPly76
回答by mR_fr0g
You only need to create one criteria object like so.
您只需要像这样创建一个标准对象。
Criteria criteria = session.createCriteria(A.class);
criteria.add(Restriction.disjunction()
.add(Restriction.eq("b.foo", "something"))
.add(Restriction.eq("c.bar", 0)));
回答by RMorrisey
In case someone else finds it useful, I found a more complicated answer to the problem which appears to be allowed by the API, though I did not get to test it before ChssPly posted his (simpler) solution:
如果其他人觉得它有用,我发现了一个更复杂的问题答案,该答案似乎是 API 允许的,尽管在 ChssPly 发布他的(更简单的)解决方案之前我没有对其进行测试:
DetachedCriteria bValues = DetachedCriteria.forClass(A.class);
bValues.createCriteria("b").add(Restrictions.eq("foo", "something"));
DetachedCriteria cValues = DetachedCriteria.forClass(A.class);
cValues.createCriteria("c").add(Restrictions.eq("bar", 0));
Restrictions.or(Subqueries.in("id", bValues), Subqueries.in("id", cValues));

