Skip to content

Commit

Permalink
Implemented Search Functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
rishabhrawat05 committed Nov 7, 2024
1 parent 6f3e150 commit 2b2e24e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
13 changes: 9 additions & 4 deletions src/main/java/com/libraryman_api/book/BookController.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,18 @@ public void deleteBook(@PathVariable int id) {

/**
* Searches book based on title, author, genre, etc.
*
* It uses a keyword parameter to filter the books, and pagination is applied to the search results.
* If no book is found it will return 204(No content found) http response.
* If keyword is null then it will return all books.
* @param keyword the Keyword to search Book
* @param pageable
* @return
*/
@GetMapping("/search/{keyword}")
public Page<Book> searchBook(@PathVariable String keyword, @PageableDefault(page = 0, size = 5, sort = "title") Pageable pageable){
return bookService.searchBook(keyword,pageable);
@GetMapping("/search")
public ResponseEntity<Page<Book>> searchBook(@RequestParam String keyword, @PageableDefault(page = 0, size = 5, sort = "title") Pageable pageable){
Page<Book> books=bookService.searchBook(keyword,pageable);
if(!books.isEmpty())
return ResponseEntity.ok(books);
return ResponseEntity.noContent().build();
}
}
12 changes: 6 additions & 6 deletions src/main/java/com/libraryman_api/book/BookRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ public interface BookRepository extends JpaRepository<Book, Integer> {
*/

@Query("SELECT b FROM Book b WHERE "
+ "b.title LIKE %:keyword% OR "
+ "b.author LIKE %:keyword% OR "
+ "b.publisher LIKE %:keyword% OR "
+ "b.genre LIKE %:keyword% OR "
+ "CAST(b.publishedYear As string) LIKE %:keyword% OR "
+ "CAST(b.copiesAvailable As string) LIKE %:keyword%")
+ "(LOWER(b.title) LIKE LOWER(CONCAT('%', :keyword, '%')) OR "
+ "LOWER(b.author) LIKE LOWER(CONCAT('%', :keyword, '%')) OR "
+ "LOWER(b.publisher) LIKE LOWER(CONCAT('%', :keyword, '%')) OR "
+ "LOWER(b.genre) LIKE LOWER(CONCAT('%', :keyword, '%')) OR "
+ "CAST(b.publishedYear AS string) LIKE %:keyword% OR "
+ "CAST(b.copiesAvailable AS string) LIKE %:keyword%)")
Page<Book> searchBook(@Param("keyword") String keyword,Pageable pageable);
}

Expand Down

0 comments on commit 2b2e24e

Please sign in to comment.