34

我试过这个:

from Table where (:par1 is null or col1 = :par1)

但它发生了

from Table where :par1 is null

始终返回表的所有行,即使 :par1 不为空。

尽管

 select * from table where col1 = 'asdf'

不返回任何行。

我不能使用本机语法,因为我的应用程序应该在不同的数据库引擎上运行

4

2 回答 2

72

nvlHQL 中的命令等价于coalesce命令。 如果不为null,则coalesce(a,b)返回,否则返回。aab

因此,您需要以下内容:

from Table where col1 = coalesce(:par1, 'asdf')
于 2009-03-02T08:31:42.210 回答
3

如果你的底层数据库是 Oracle,那么你可以使用 nvl 函数,我试过了,它对我有用。

Query query = session.createQuery(
                    " select ft from FeatureToggle ft left outer join ft.featureToggleCustomerMap "
                    + " ftcm where nvl(ftcm.custId,:custId) = :custId");

query.setParameter("custId", Long.valueOf(custId));

您的用例可能不同,如果数据库是 nvl,您可以根据您的要求使用 nvl 函数,不确定其他数据库的影响,因为我仅将此代码用于 Oracle。希望能帮助到你。

于 2016-04-22T16:05:45.673 回答