当使用hibernate的标准查询时,你如何“或”标准呢?

我试图做一个基本的“或”在三个领域使用hibernate条件查询。

class Whatever{ string name; string address; string phoneNumber; } 

我想build立一个标准查询,我的searchstring可以匹配“名称”或“地址”或“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或c2)和c3或任何复杂expression式都可以做同样的事情。

 //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. 

以防万一任何人都应该在NHibernate的同一个问题上碰到这个问题:

 ICriteria c = session.CreateCriteria(typeof (Whatever)) .Add(Expression.Disjunction() .Add(Expression.Eq("name", searchString)) .Add(Expression.Eq("address", searchString)) .Add(Expression.Eq("phoneNumber", searchString))); 

这些条件可以通过使用析取的查询的不同级别来应用

 Criteria query = getCriteria("ENTITY_NAME"); query.add(Restrictions.ne("column Name", current _value)); Disjunction disjunction = Restrictions.disjunction(); if (param_1 != null) disjunction.add(Restrictions.or(Restrictions.eq("column Name", param1))); if (param_2 != null) disjunction.add(Restrictions.or(Restrictions.eq("column Name", param_2))); if (param_3 != null) disjunction.add(Restrictions.or(Restrictions.eq("column Name", param_3))); if (param_4 != null && param_5 != null) disjunction.add(Restrictions.or(Restrictions.and(Restrictions.eq("column Name", param_4 ), Restrictions.eq("column Name", param_5 )))); if (disjunction.conditions() != null && disjunction.conditions().iterator().hasNext()) query.add(Restrictions.and(disjunction)); return query.list();