问题
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 PreparedStatement
s. 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