将空列表作为参数传递给

将空列表作为参数传递给

本文介绍了将空列表作为参数传递给 JPA 查询会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将空列表传递到 JPA 查询中,则会出现错误.例如:

If I pass an empty list into a JPA query, I get an error. For example:

List<Municipality> municipalities = myDao.findAll();  // returns empty list
em.createQuery("SELECT p FROM Profile p JOIN p.municipality m WHERE m IN (:municipalities)")
    .setParameter("municipalities", municipalities)
    .getResultList();

因为列表是空的,Hibernate 在 SQL 中将其生成为IN()",这给我带来了 Hypersonic 数据库的错误.

Because the list is empty, Hibernate generates this in SQL as "IN ()", which gives me error with Hypersonic database.

Hibernate 问题跟踪中有一张票那里的评论/活动并不多.我也不知道其他 ORM 产品或 JPA 规范是否支持.

There is a ticket for this in Hibernate issue tracking but there are not many comments/activity there. I don't know about support in other ORM products or in JPA spec either.

我不喜欢每次都必须手动检查空对象和空列表的想法.是否有一些众所周知的方法/扩展?您如何处理这些情况?

I don't like the idea of having to manually check for null objects and empty lists every time. Is there some commonly known approach/extension to this? How do you handle these situations?

推荐答案

根据 JPA 1.0 规范中的 4.6.8 In Expressions 部分:

According to the section 4.6.8 In Expressions from the JPA 1.0 specification:

逗号分隔列表中必须至少有一个元素来定义 IN 表达式的值集.

换句话说,无论 Hibernate 解析查询和传递 IN() 的能力如何,无论特定数据库对此语法的支持如何(PosgreSQL 不根据 Jira 问题)),如果您希望代码可移植,则应在此处使用动态查询(我通常更喜欢使用 Criteria API 进行动态查询).

In other words, regardless of Hibernate's ability to parse the query and to pass an IN(), regardless of the support of this syntax by particular databases (PosgreSQL doesn't according to the Jira issue), you should use a dynamic query here if you want your code to be portable (and I usually prefer to use the Criteria API for dynamic queries).

这篇关于将空列表作为参数传递给 JPA 查询会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 19:43