2012-09-13 70 views
0

我需要的所有不同的人的名字<>空:Hibernate的标准+投影没有结果

List<Criterion> conditions = new ArrayList<Criterion>(); 
conditions.add(Restrictions.ne("name", null)); 
Projection projection = Projections.distinct(Projections.property("name")); 
List<People> result = dao.findByCriteria(conditions, projection); 

其中:

public List<T> findByCriteria(List<Criterion> list, Projection projection) { 

    try {     
     Criteria criteria = getSession().createCriteria(entityClass); 
     if (list != null) { 
      for (int i = 0; i < list.size(); i++) { 
       criteria.add(list.get(i)); 
      } 
     } 
     if (projection != null) { 
      criteria.setProjection(projection); 
     } 
     List result = criteria.list(); 
     return result; 
    } catch (Exception e) { 
     // log 
    } 
} 

和生成的查询是:

Hibernate: select distinct this_.name as y0_ from Mrdb this_ where this_.name<>? 

但我没有结果!事实上,只使用投影或仅使用一个标准列表查询工作正常,但使用两者都没有结果。

我错过了什么?

感谢

+0

看起来确定。你是否手动执行了生成的SQL查看结果是否真的回来? – Firo

+0

@jelies:你的回答是正确的。你应该取消删除它。 –

+0

谢谢@JBNizet!但一旦发布,我认为这与问题无关,因为在OP问题上生成的查询似乎没有问题。 – jelies

回答

1

尝试:

conditions.add(Restrictions.isNotNull("name")); 

生成的查询会是这样的:

Hibernate: select distinct this_.name as y0_ from Mrdb this_ where this_.name is not null 

编辑:

由于@JBNizet问题的评论说:

(生成的)查询很好,但在SQL中,就像在HQL中那样,比较 将null总是导致false。要与null进行比较,必须始终使用 为空或不为空。

0

为什么不在该条件中添加限制条件?

例如,在您的实体fieldName领域:

Criteria criteria = getSession().createCriteria(entityClass); 
criteria.add(Restrictions.isNotNull("fieldName"));