在本机 sql 查询中使用 IN 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/831990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using IN clause in a native sql query
提问by topchef
We are trying to dynamically generate an IN clause for a native sql query to return a JPA entity. Hibernate is our JPA provider. Our code looks something like this.
我们正在尝试为本机 sql 查询动态生成 IN 子句以返回 JPA 实体。Hibernate 是我们的 JPA 提供者。我们的代码看起来像这样。
@NamedQuery(
name="fooQuery",
queryString="select f from Foo f where f.status in (?1)"
)
....
Query q = entityManager.createNamedQuery("fooQuery");
q.setParameter(1, "('NEW','OLD')");
return q.getResultList();
This doesn't work, the in clause does not recognize any of the values passed in via this manner. Does anyone know of a solution to this problem?
这不起作用, in 子句无法识别通过这种方式传入的任何值。有谁知道这个问题的解决方案?
回答by topchef
JPA supports named list parameters, in your case:
JPA 支持命名列表参数,在您的情况下:
@NamedQuery(
name="fooQuery",
queryString="select f from Foo f where f.status in (?1)"
)
Query q = entityManager.createNamedQuery("fooQuery");
List<String> listParameter = new ArrayList<>();
listParameter.add("NEW");
listParameter.add("OLD");
q.setParameter(1, listParameter);
return q.getResultList();
回答by Paul Sonier
I would recommend to not use a composite parameter for your query, but to split it out individually. Don't specify ('NEW','OLD')
; specify separate parameters of 'NEW'
and 'OLD'
. That may help.
我建议不要为您的查询使用复合参数,而是将其单独拆分。不要指定('NEW','OLD')
;指定的单独的参数'NEW'
和'OLD'
。这可能会有所帮助。
This, of course, may cause problems if your parameter lengths are undefined.
当然,如果您的参数长度未定义,这可能会导致问题。