我正在尝试使用hibernate条件查询在三个字段上执行基本的"OR".
例
class Whatever{ string name; string address; string phoneNumber; }
我想构建一个条件查询,我的搜索字符串可以匹配"name"或"address"或"phoneNumber".
你想用Restrictions.disjuntion()
.像这样
session.createCriteria(Whatever.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", queryString)) .add(Restrictions.eq("address", queryString)) .add(Restrictions.eq("phoneNumber", queryString)) );
请参阅此处的Hibernate文档.
假设你有一个hibernate会话,那么类似下面的东西应该工作:
Criteria c = session.createCriteria(Whatever.class); Disjunction or = Restrictions.disjunction(); or.add(Restrictions.eq("name",searchString)); or.add(Restrictions.eq("address",searchString)); or.add(Restrictions.eq("phoneNumber",searchString)); c.add(or);
//Expression : (c1 AND c2) OR (c3) Criteria criteria = session.createCriteria(Employee.class); Criterion c1 = Restrictions.like("name", "%e%"); Criterion c2 = Restrictions.ge("salary", 10000.00); Criterion c3 = Restrictions.like("name", "%YYY%"); Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3); criteria.add(c4);
//可以为(c1 OR c2)AND c3或任何复杂表达式做同样的事情.
//Expression : (c1 AND c2) OR (c3) Criteria criteria = session.createCriteria(Employee.class); Criterion c1 = Restrictions.like("name", "%e%"); Criterion c2 = Restrictions.ge("salary", 10000.00); Criterion c3 = Restrictions.like("name", "%YYY%"); Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3); criteria.add(c4); //Same thing can be done for (c1 OR c2) AND c3, or any complex expression.