有没有办法在使用Hibernate时在命名查询中指定可选参数(例如,当搜索参数是从表单提供时,并非所有参数都是必需的)?我正在使用本机SQL查询,但该问题可能也适用于命名的HQL查询。
我很确定这个答案是否定的,但我还没有在文档中找到明确的答案。
有没有办法在使用Hibernate时在命名查询中指定可选参数(例如,当搜索参数是从表单提供时,并非所有参数都是必需的)?我正在使用本机SQL查询,但该问题可能也适用于命名的HQL查询。
我很确定这个答案是否定的,但我还没有在文档中找到明确的答案。
AFAIK, there is no such thing so you'll have to write a dynamic query for this. Maybe have a look at this previous answer showing how to do this in HQL (that you can transpose to SQL) and also showing how the Criteria API makes it simpler and is thus better suited for this job in my opinion.
Update: (answering a comment from the OP) Working with a legacy database can be indeed tricky with Hibernate. Maybe you can use a dynamic native query and return non-managed entities though. But on the long run, things might get worse (I can't tell that for you). Maybe Hibernate is not the best choice in your case and something like iBATIS would give you the flexibility you need.
不幸的是,“可选或空参数”下的解决方案不适用于 IN 列表。我不得不改变查询如下......
命名查询定义:
select ls from KiCOHeader co
...
join lu.handlingType ht
where (:inHandlingTypesX = 1 OR ht.name in (:inHandlingTypes))
代码:
Set<KiHandlingTypeEnum> inHandlingTypes = ...
Query query = persistence.getEm().createNamedQuery("NAMED_QUERY");
query.setParameter("inHandlingTypesX", (inHandlingTypes == null) ? 1 : 0);
query.setParameter("inHandlingTypes", inHandlingTypes);
List<KiLogicalStock> stocks = query.getResultList();
工作很有趣。
处理可选列表参数的另一种解决方案是使用COALESCE函数检查 null。Hibernate 支持COALESCE从列表中返回第一个非 null 参数,当列表中有多个项目时,允许您在不破坏语法的情况下检查列表中的 null。
带有可选参数和列表参数的 HQL 示例:
select obj from MyEntity obj
where ( COALESCE( null, :listParameter ) is null or obj.field1 in (:listParameter) )
and ( :parameter is null or obj.field2 = :parameter )
这对我来说适用于 SQL Server 方言。
对于那些对 NULL 值有问题的人,另一种选择是使用替代值。在我的例子中,我只为我的类别字段使用了正值,这允许我使用我的备用值 = -1。
因此,在执行查询之前,可以做一个小验证:
if(value==null) {
value = -1;
}
....
....
select p from Product p WHERE :value = -1 or p.category = :value