我试过这个:
from Table where (:par1 is null or col1 = :par1)
但它发生了
from Table where :par1 is null
始终返回表的所有行,即使 :par1 不为空。
尽管
select * from table where col1 = 'asdf'
不返回任何行。
我不能使用本机语法,因为我的应用程序应该在不同的数据库引擎上运行
nvl
HQL 中的命令等价于coalesce
命令。 如果不为null,则coalesce(a,b)
返回,否则返回。a
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。希望能帮助到你。