Palak Kharbanda
Palak Kharbanda

Reputation: 95

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

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 :)

Upvotes: 0

Views: 1745

Answers (2)

Jens Schauder
Jens Schauder

Reputation: 81988

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

Upvotes: 1

lamik
lamik

Reputation: 99

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

Upvotes: 1

Related Questions