简体   繁体   English

使用设置参数在JPA查询中插入特殊字符

[英]Insert special characters in JPA query with set parameter

Is there a way in JPA 2.0 to set parameter of a query with special characters? 在JPA 2.0中,是否可以使用特殊字符设置查询参数? I mean, if I do: query.setParameter(field, "%" + value.toString() + "%"); 我的意思是,如果我这样做: query.setParameter(field, "%" + value.toString() + "%"); , it takes % as special (wildcard) character? ,它需要%作为特殊(通配符)字符吗? It seems to me it's not true in this case, beacuse my search doesn't work with truncated words... Can You help me?? 在我看来,这不是真的,因为我的搜索不适用于截断的单词...您能帮我吗?

If you are using 如果您正在使用

LIKE :feild 

for 对于

query.setParameter(field, "%" + value.toString() + "%");

Then value remains free from the '%' sign. 然后,值将保持无“%”符号。 You can try to use % in your query and send value from setParameter() method. 您可以尝试在查询中使用%并从setParameter()方法发送值。

You can also try CreteriaBuilderInterface of JPA. 您也可以尝试JPA的CreteriaBuilderInterface http://www.objectdb.com/java/jpa/query/jpql/string . http://www.objectdb.com/java/jpa/query/jpql/string

you have to escape the query. 您必须转义查询。 try to use "\\\\%" instead 尝试使用"\\\\%"代替

what ever you pass in as a query parameter that will pass on to query and back to database. 您作为查询参数传递的所有信息将传递给查询并返回数据库。 So to the choice of escape character of the query parameter will depend on database. 因此,对查询参数的转义字符的选择将取决于数据库。 Like in mysql it is "\\'" for "'" and "\\%" for "%" so if I want to send "john's 10% commission" as query parameter to mysql, i will try query.setParameter(field, "john\\\\'s 10\\\\% commission") ; 像在mysql中一样,它是“ \\”代表“'”,“ \\%”代表“%”,因此,如果我想将“约翰的10%佣金”作为查询参数发送给m​​ysql,我将尝试使用query.setParameter(field, "john\\\\'s 10\\\\% commission") in your case query.setParameter(field, "\\\\%" + value.toString() + "\\\\%"); 在您的情况下query.setParameter(field, "\\\\%" + value.toString() + "\\\\%"); should work. 应该管用。 But check the documentation of the database to find out escape character for special cases. 但是,请检查数据库文档以找出特殊情况下的转义符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM