SpringDataJpa: Multiple ContainingIgnoreCase

落爺英雄遲暮 提交于 2020-01-25 00:35:07

问题


I have something like below. basically I want to get all the books contains certain keywords in their title or description. Spring keep giving me error on this method. Single select of either Title or Descr works, but I am just not able to put them together. What am I missing?

works:

findBookByTitleContainingIgnoreCase(String keyWord)

findBookByDescrContainingIgnoreCase(String keyWord)

doesn't work: findBookByTitleContainingIgnoreCaseOrDescrContainingIgnoreCase(String keyWord)


回答1:


This will work:

findByTitleContainingIgnoreCaseOrDescrContainingIgnoreCase(String title, String descr);

You can then call this method as bookRepository.findByTitleContainingIgnoreCaseOrDescrContainingIgnoreCase(keyword, keyword)

An easy way to remember how to form queries with Spring Data JPA is to keep in mind that method names eventually become JDBC PreparedStatements. Each keyword (class attribute) in the method name becomes a parameter in the PreparedStatement. Consequently, each of the parameters must be bound to a value when the PreparedStatement is executed. Therefore, the method must have equal number of arguments for the PreparedStatement to execute correctly.

When you apply this thinking to your problem, you will see that your method name has two keywords - Title and Descr but only one parameter. So, the second parameter in the PreparedStatement remains unbound when the PreparedStatement is executed; hence the error. Supplying both parameters solves the problem.

Sample code with working test cases on Github.




回答2:


findBookByTitleContainingIgnoreCaseOrDescrContainingIgnoreCase(String keyWord, String keyWord2); fixed my problem.



来源:https://stackoverflow.com/questions/33792288/springdatajpa-multiple-containingignorecase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!