我试过了:

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

但它恰好发生了

from Table where :par1 is null

总是返回表的所有行,即使:par1不为null。

,而

 select * from table where col1 = 'asdf'

不会返回任何行。

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

有帮助吗?

解决方案

HQL中 nvl 命令的等价物是 coalesce 命令。如果 a 不为null, coalesce(a,b)将返回 a ,否则 b

所以你想要的东西是:

from Table where col1 = coalesce(:par1, 'asdf')

其他提示

如果你的底层数据库是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。 希望它有所帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top