如何阻止Spring JPA对查询方法的参数进行转义?

huangapple go评论61阅读模式
英文:

How can I stop Spring JPA from escaping the arguments to a query method?

问题

在我的Spring JPA应用程序中,我有一个名为findAllByNameContaining的查询方法,适用于简单的、单词类型的参数。

例如,假设数据库中有一条记录,其中字段值为'Foo bar zed',如果使用'Foo'调用查询方法,它将返回该记录。

然而,我希望如果使用'Foo zed'调用查询方法,也能返回该记录。我尝试将搜索词中的空格替换为'%'。但是这样返回的结果为空,并且当我检查生成的SQL时,我看到我添加到搜索词中的'%'被转义了。我理解这很可能是为了防止SQL注入,但我想知道是否有办法停止Spring进行转义。我可以自己验证参数以防止SQL注入。

英文:

In my Spring JPA application, I have a query method called findAllByNameContaining that works for simple, one word arguments.

For instance, with a record in the database having a field value of 'Foo bar zed', the query method will return the record if called with 'Foo'.

However, I'd like the record to be retured if the query method is called with 'Foo zed'. I tried to replace spaces in the search term with '%'. This returned nothing and when I checked the generated SQL, I see that the '%' that I added to the search term was escaped. I understand this is likely to be protection against SQL injection, but I was wondering if there's anyway to stop Sopring escaping. I can validate the arguments myself to protect against SQL injection.

答案1

得分: 1

使用findByNameLike替代,并在参数中放置通配符在您想要的任何位置。

请注意,您必须在参数中提供所有的通配符,Spring Data不会自动添加任何通配符,但也不会进行任何转义。

英文:

Use findByNameLike instead and put the wildcards in the argument where ever you want.

Note that you have to provide all wildcards in the argument, Spring Data won't add any on its own but it won't escape any either.

huangapple
  • 本文由 发表于 2020年10月5日 21:23:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64209473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定