Home > Enterprise >  I want to use LIKE operator with OR operator in Jpa Spring Boot
I want to use LIKE operator with OR operator in Jpa Spring Boot

Time:06-29

I am retrieving books from database using three query parameters - name, author and description. So, I am using the following method in BookRepository.

public List<BookRepoRto> findByNameOrAuthorOrDescription(String name, String author, String description);

This is working fine. But suppose there is a book whose author is "Mahatama Gandhi". But while calling the method, user is passing the author's name as "gandhi"

localhost:8070/api/bookstoreapp/books/nameorauthorordesc?name=gandhi

So, problem is that the method

public List<BookRepoRto> findByNameOrAuthorOrDescription(String name, String author, String description);

is not working in that case. Same thing you can consider for description because obviously, user will not write whole description of the book in the query param to get the book he is thinking of because probably, he won't be knowing the exact description which is in the database.

So, I tried writing the following method instead of the upper one. In this method, I am trying to use the Like operator along with the Or operator but I am not getting the desired output. Please help!

public List<BookRepoRto> findByNameLikeOrAuthorLikeOrDescriptionLike(String name, String author, String description);

I know that this problem can be solved using the @Query annotation but still I want to know if I can create the required jpa method which can fulfill the conditions :)

CodePudding user response:

When you use the Like operator you'll need to provide wildcards in the parameter. In order to get an equivalent query like the one you provided in the comments

SELECT * FROM books b 
WHERE b.name LIKE :name% 
or b.author LIKE %:author% 
or b.description LIKE %:description%

You should use

findByNameStartsWithOrAuthorContainsOrDescriptionContains(
    String name, 
    String author, 
    String description
)

See https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords

CodePudding user response:

You can use the specification feature for this. It make you able to combine different predicates using FP-like style: https://www.baeldung.com/spring-data-criteria-queries

  • Related