Home > database >  Getting error when implementing Pageable Interface in SpringBoot?
Getting error when implementing Pageable Interface in SpringBoot?

Time:10-26

This is my sample code in which I am trying to fetch the find the latest product through pagable interface ,

try{
Repo product = repo.findByIdDateAndValueExists(data.getId, data.getDate, request).getContent().get(0);
}catch(Exception e){
  LOGGER.error("Failed :: something went wrong: {}", e.getMessage(), e);
}

Here is my repositorycode

@Query(value = "{'ID': ?0, 'Date' : ?1 ,'value':{'$exists': true}}")
Page<Repo> findByIdDateAndValueExists(String Id ,String Date,Pageable pageable);

Now what is happening in some case I am getting java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 And its breaking the entire flow of code , can someone pls suggest the correct way to handle such exception in such case , Any sort of help is appreciated .

CodePudding user response:

you can first check the size of result and then try to retrieve an element. something like

List<Repo> resutl = addressRepository.findByIdDateAndValueExists().getContent();
if (!result.isEmpty() {
 .....

CodePudding user response:

In JPA Query indexing starts with 1 so use this syntax for your custom query

@Query(value = "{'ID': ?1, 'Date' : ?2 ,'value':{'$exists': true}}") Page findByIdDateAndValueExists(String Id ,String Date,Pageable pageable);

CodePudding user response:

Before working on the whatever the result you have got, first you need to check whether it is returning any data or not.

According to your code findByIdDateAndValueExists() metho addressRepository will return Page of entity i.e.,

Page<Repo> page = repo.findByIdDateAndValueExists(data.getId, data.getDate, request);
// it will give how many pages it has return
int totalPages = page.getTotalPages();
if(totalPages>=1){
 List<Repo> products = page.getContent();
        .
        .
        .
        .
}else{
// do nothing
}
  • Related