javaspringmongorepository

How list of object return a Spring Page with Mongo repository?


I have a GET request in which the user can pass a list of book codes as a parameter. Like this:

@GetMapping("/books")
public ResponseEntity<Page<BooksView>> findAvailableBooks(@RequestParam(value = "codes") String[] codes

I need to take this array of codes and verify which book codes exist in the database and if they are available in stock to return them as a Spring page. I tried this:

1) First check if the code array is filled

2) If so, for each code in the array I check with mongo repository if that code exists in the database and if the available is true

3) If so, I add the current code to a list

4) But I don't know if this logic works (is there a simpler or cleaner way to do it?) and I also don't know how to treat this list so that the return is a Page

public Page<Book> findBooks(String[] codes) {

        if(codes.length > 0) {

            List<String> listOfCodes = null;

            for (String code : codes){

                if(repository.existsByCodeAndAvailable(Long.parseLong(code))){
                   listOfCodes.add(code);
                }
            }

        return ???

        }
}   

Solution

  • you can write custom method in the repository like below,

    public interface BookRepository extends MongoRepository<Book, String> {
    
       Page<Book> findAllByCodeIn(String[] codes, Pageable pageable);
    }
    

    you can call the custom method from your service,

    bookRepository.findAllByCodeIn(codes, PageRequest.of(0, 10))
    

    I have the below test data inside my db,

    bookRepository.save(new Book("S001", "Java"));
    bookRepository.save(new Book("S002", "Spring"));
    bookRepository.save(new Book("S003", "Kotlin"));
    

    Different test case scenario's

    GET http://localhost:8080/books?codes=
    
    {
     "content": [],
     "pageable": {
     "sort": {
       "sorted": false,
       "unsorted": true,
       "empty": true
     },
     "offset": 0,
     "pageNumber": 0,
     "pageSize": 10,
     "paged": true,
     "unpaged": false
    },
    "totalPages": 0,
    "totalElements": 0,
    "last": true,
    "size": 10,
    "number": 0,
    "numberOfElements": 0,
    "first": true,
    "sort": {
      "sorted": false,
      "unsorted": true,
      "empty": true
     },
     "empty": true
    }
    

    Test 2:

    GET http://localhost:8080/books?codes=S001
    {
     "content": [
       {
          "code": "S001",
          "name": "Java"
       }
    

    ],

    Test 3:

    GET http://localhost:8080/books?codes=S001,S002
    {
      "content": [
       {
         "code": "S001",
         "name": "Java"
       },
       {
        "code": "S002",
         "name": "Spring"
       }
     ],