Java 处理“NOT IN(:param)”时的JPA setParameter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1947323/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:42:26  来源:igfitidea点击:

JPA setParameter when dealing with "NOT IN (:param)"

javajpanamed-query

提问by rafa.ferreira

I'm trying to set a parameter in my query, for example:

我正在尝试在我的查询中设置一个参数,例如:

select * from Cars where Cars.color NOT IN (:color_params)

And when I'm adding the parameter in my JavaClass is like:

当我在我的 JavaClass 中添加参数时,就像:

...
query.setParameter("color_params", "RED,BLUE");
...

And this is not working, is only working with only one parameter.
I've tried with "'RED','BLUE'"and is not working to.

这不起作用,仅适用于一个参数
我已经尝试过,但"'RED','BLUE'"没有成功。

If I put my parameters in the query is working for example:

如果我把我的参数放在查询中,例如:

select * from Cars where Cars.color NOT IN ('RED','BLUE')

What I'm doing wrong!?

我做错了什么!?

Thanks in advance

提前致谢

采纳答案by KLE

You are supposed to pass a List.

你应该通过一个列表。

List<String> colors = ....;
String query = "select * from Cars where Cars.color NOT IN (:color_params)";
Map<String, Object> params = new HashMap<String, Object>();
params.put("color_params", colors);
// ... execute the query with the param.

You could also do:

你也可以这样做:

query.setParameter("color_params", colors);


As a general rule, it is often prefered to pass parameters to a fixed query, instead of customizing the String. The advantages could be:

作为一般规则,通常更喜欢将参数传递给固定查询,而不是自定义字符串。优点可能是:

  1. Reduced parsing: JPA implementation (at least Hibernate) have a hard work parsing each query. So the parsed query goes into a cache, to be reused. If the query string is build at runtime from parameters, it might never be twice the same, so a lot of time, computing power and cache memory are lost. But if you use the same query string with different parameters, bingo : fast, low memory use, low cpu requirement.
  2. Prevent SQL injection. This guarantee is offered if you use parameters. If you build your query string with the parameters, you have to provide yourself this guarantee ...!
  1. 减少解析:JPA 实现(至少是 Hibernate)在解析每个查询时需要付出艰苦的努力。所以解析后的查询进入缓存,以供重用。如果查询字符串是在运行时根据参数构建的,它可能永远不会是相同的两倍,因此会丢失大量时间、计算能力和缓存。但是,如果您使用具有不同参数的相同查询字符串,宾果游戏:速度快,内存使用量低,CPU 要求低。
  2. 防止 SQL 注入。如果您使用参数,则提供此保证。如果您使用参数构建查询字符串,则必须为自己提供此保证......!

回答by Aaron Digulla

You must pass in a list of strings, not a single string. JPA doesn't parse your values, you must split them yourself.

您必须传入字符串列表,而不是单个字符串。JPA 不解析您的值,您必须自己拆分它们。