将 IN 子句列表添加到 JPA 查询
我构建了一个如下所示的 NamedQuery:
@NamedQuery(name = "EventLog.viewDatesInclude",
query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND "
+ "el.timeMark <= :dateTo AND "
+ "el.name IN (:inclList)")
我想要做的是用项目列表而不是一个项目填充参数 :inclList。例如,如果我有一个 new List
如何在 :inclList 参数中获取它?它只让我编写一个字符串。例如:
setParameter("inclList", "a") // works
setParameter("inclList", "a, b") // does not work
setParameter("inclList", "'a', 'b'") // does not work
setParameter("inclList", list) // throws an exception
我知道我可以构建一个字符串并从中构建整个查询,但我想避免开销。有更好的方法吗?
相关问题:如果列表非常大,有什么好的方法来构建这样的查询吗?
I have built a NamedQuery that looks like this:
@NamedQuery(name = "EventLog.viewDatesInclude",
query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND "
+ "el.timeMark <= :dateTo AND "
+ "el.name IN (:inclList)")
What I want to do is fill in the parameter :inclList with a list of items instead of one item. For example if I have a new List<String>() { "a", "b", "c" }
how do I get that in the :inclList parameter? It only lets me codify one string. For example:
setParameter("inclList", "a") // works
setParameter("inclList", "a, b") // does not work
setParameter("inclList", "'a', 'b'") // does not work
setParameter("inclList", list) // throws an exception
I know I could just build a string and build the whole Query from that, but I wanted to avoid the overhead. Is there a better way of doing this?
Related question: if the List is very large, is there any good way of building query like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将
IN
与集合值参数一起使用时,不需要(...)
:When using
IN
with a collection-valued parameter you don't need(...)
:正确的 JPA 查询格式是:
如果您使用旧版本的 Hibernate 作为提供程序,则必须编写:
但这是一个错误 (HHH-5126)(编辑:现已解决)。
The proper JPA query format would be:
If you're using an older version of Hibernate as your provider you have to write:
but that is a bug (HHH-5126) (EDIT: which has been resolved by now).
适用于我的 JPA 2、Jboss 7.0.2
Works for me with JPA 2, Jboss 7.0.2
您应该转换为
List
,如下所示:You should convert to
List
as shown below: