How to initialize Spring Data JPA Page to null?
Asked Answered
U

4

8

This is a code snippet of my project. Here I'm trying to get paginated data using Spring Data JPA. The pagination part works fine. However when searchParameter is NULL then I just want to return empty create a blank page in my UI

public Page<AccessLog> getDataInRange(long fromTime, long toTime, String searchParameter, Integer start,
                                          Integer length) {
        Page<AccessLog> accessPage;
        if (searchParameter != null) {
            accessPage = accessRepository.findBySystemTimestampBetween(fromTime, toTime,
                    new PageRequest(start, length));
        } else
            accessPage = null;
        return accessPage;
    }

However, this give an error when search parameter is null

Exception during execution of SpringSecurity application java.lang.NullPointerException: null

which caused because of that "null" value set as accessLogPage.

Any ideas?

Uvea answered 6/6, 2017 at 9:31 Comment(1)
Is it possible to return a blank(empty) Page in Spring Data JPA?Uvea
C
21

From Spring Boot 2.0, you can use Page.empty() to return empty Page.

Collazo answered 6/10, 2019 at 5:41 Comment(0)
Y
2

You can use implementation of Page

Page<AccessLog> accessPage = new PageImpl<>(Collections.emptyList());
Yuri answered 23/6, 2022 at 13:41 Comment(0)
T
1

The searchParameter should be handled in the controller itself.

Try something like this in your controller

@Controller
public class BaseController {

    @RequestMapping("/")
    public ModelAndView welcome(...) {

        //get your searchParameter here

        if(searchParameter == null) {
            return new ModelAndView("blank-page");
        }

        //call your service layer to fetch the data and then return the actual page

        ModelAndView modelAndView = new ModelAndView("actual-page");
        modelAndView.addObject("data", FETCHED_DATA_FROM_SERVICE_LAYER); 
        return new ModelAndView("actual-page");

    }

}
Triumph answered 6/6, 2017 at 11:51 Comment(0)
L
0

For those on Spring 1.5.x versions, there is currently no easy way to return an empty page but you could check the returned Page (from repository) for null values and then return the appropriate response from the controller.

The following code is for returning an empty response if Page object is null:

  ResponseEntity<?> sample(...params) {

        Page<AccessLog> page = ....

        if(page != null){
            return new ResponseEntity<>(page, HttpStatus.OK);
        }
        else{
            return new ResponseEntity<>(HttpStatus.OK);
        }
    }
Lansquenet answered 14/7, 2021 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.