如何使用Hibernate eqOrIsNull()

我这样在MySQL中有两行

+---------+---------+ | foo | bar | +---------+---------+ | | NULL | | | | +---------+---------+ 

空的是空字符串""

现在我想得到他们两个。 我在两列上都使用CriteriaRestrictions.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". 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("") 。 我应该使用eqisNull分离,就像Gregory 回答的那样 。

检查此代码是否符合您的要求 –

 criteria.add(Restrictions.or(Restrictions.eq("foo", ""), Restrictions.isNull("foo"))) .add(Restrictions.or(Restrictions.eq("bar", ""), Restrictions.isNull("bar"))); 

此代码段使用Hibernate 3.5.0-CR-2 API。

对命名属性应用“相等”约束。 如果值为null,则应用“is null”。

这意味着,只有在将NULL作为值传递时才会应用is null 。 如果您将任何其他字符串指定为值,则仅对该值应用equal

当您不确定在运行时作为参数值的参数传递的实际值时,这非常有用。 在这种情况下,以传统方式,您需要根据非空条件放置非空的检查和写入条件,或者您需要以Gregory的答案提到的方式编写标准。

记住所有这些事实,你应该回答你的问题。 您只获得那些包含空值而不是具有NULL值的行,因为您已将空字符串指定为第二个参数。 如果将NULL指定为第二个参数,则只能获得具有NULL值的行。

如果这对您有帮助,请告诉我。