【发布时间】:2013-10-19 21:30:31
【问题描述】:
我在 MySQL 中有两行这样的
+---------+---------+
| foo | bar |
+---------+---------+
| | NULL |
| | |
+---------+---------+
其中空是空字符串""。
现在我想同时获得它们。我在两列上都使用了Criteria 和Restrictions.eqOrIsNull(),但它总是只返回一行。
代码是这样的
criteria.add(Restrictions.eqOrIsNull("foo", ""));
.add(Restrictions.eqOrIsNull("bar", ""));
当我仅在foo 上添加条件时,它会返回两行。但是对于bar,它只返回第二个,它是空的。
javadoc 说,Apply an "equal" constraint to the named property. If the value is null, instead apply "is null". 那么是我弄错了,还是应该以其他方式使用它?
更新:
对不起,我太粗心了。文档清楚地说明了这一点。此方法根据传递给它的value 工作,而不是存储在 DB 中的命名属性的实际值。
Github上的源码:
public static Criterion eqOrIsNull(String propertyName, Object value) {
return value == null
? isNull( propertyName )
: eq( propertyName, value );
}
所以在我的例子中,eqOrIsNull 返回eq("")。我应该使用 eq 和 isNull 的析取,比如 Gregory answered。
【问题讨论】:
-
对于此类问题,您应该启用调试日志记录。它会让hibernate打印正在执行的sql。
-
有点像
select foo,bar from table where foo=? and bar=?