将空列表作为参数传递给JPA查询会引发错误 [英] Passing empty list as parameter to JPA query throws error

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

问题描述

如果我将一个空列表传递给JPA查询,那么会出现错误。例如:

 列表<市政>都市= myDao.findAll(); //返回空列表
em.createQuery(SELECT p FROM Profile p JOIN p.municipality m WHERE m IN(:municipalities))
.setParameter(municipalities,municipalities)
.getResultList();

因为列表是空的,所以Hibernate在SQL中以IN() Hypersonic数据库出错。



有一张票据在 Hibernate问题跟踪,但那里没有太多评论/活动。我不知道支持其他ORM产品或JPA规范。

我不喜欢必须手动检查空对象和空列表的想法每次。是否有一些众所周知的方法/扩展?如何处理这些情况?根据 4.6.8 In Expressions 中的 部分, JPA 1.0规范:
$ b


逗号分隔列表中必须至少有一个元素定义<$ c $的值集c> IN 表达式。

换句话说,不管Hibernate能够解析查询并通过一个 IN(),无论特定数据库对此语法的支持如何(PosgreSQL不根据Jira问题),如果您想要使用动态查询你的代码是可移植的(我通常更喜欢使用Criteria API进行动态查询)。


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();

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

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?

解决方案

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

There must be at least one element in the comma separated list that defines the set of values for the IN expression.

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查询会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆