Thursday, September 10, 2020

Pagination and Sorting With Spring Data JPA

 

Pagination and Sorting With Spring Data JPA

 

Pagination is very useful when we have to deal with large set of data  and we want to present it to the view layer  in smaller data sets.

 We also need to sort that data by some criteria while applying paging.

In this tutorial,

 we will explain how to implement pagination and sort using Spring Data JPA and access throgh the GET request.

Further you can use any view logic to display the data but here we will just use get api

 

Repository:

@Repository

public interface TodoJPARepository extends JpaRepository<Todo, Long>{

      List<Todo> findByUsername(String username);

      Page<Todo> findByUsername(String username, Pageable pageable);

}

 

Suppose I need the sorted and pageable data when get request is sent to below URL:

GET : http://127.0.0.1:8080/jpa/users/dinesh/todos/v2/1/3?sortField=id&sortDirection=desc

 

{

    "currentPage"1,

    "totalPages"4,

    "totalItems"10,

    "sortField""id",

    "sortDirection""asc",

    "todosList": [

        {

            "id"11010,

            "username""dinesh",

            "description""Learn Spring Boot5 D",

            "targetDate""2020-09-10T03:52:05.232+0000",

            "done"false

        },

        {

            "id"11009,

            "username""dinesh",

            "description""Learn Spring Boot4 D",

            "targetDate""2020-09-10T03:52:05.232+0000",

            "done"false

        },

        {

            "id"11008,

            "username""dinesh",

            "description""Learn Spring Boot3 D",

            "targetDate""2020-09-10T03:52:05.232+0000",

            "done"false

        }

    ]

}

 

Controller Get Method Logic:

@GetMapping("/jpa/users/{username}/todos/v2/{page}/{pagesize}")

               

 public TodoResponse getUserTodos(
                 

@PathVariable(value = "username") String username,

@PathVariable(value = "page") int page

@PathVariable(value = "pagesize") int pagesize,
@RequestParam(value = "sortField", defaultValue = "targetDate") String   sortField,

@RequestParam(value = "sortDirection", defaultValue = "ASC") String  sortDirection

 

                 {

 

                  //Response Object

                                TodoResponse todoResponse = new TodoResponse();

 

            // Sorting

            // Create Sort method based on the request parameter

 Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())                                         ?    Sort.by(sortField).ascending() : Sort.by(sortField).descending();

 

     // Create PageRequest Object and pass page and sorting parameter

                                Pageable pageable = PageRequest.of(page - 1, pagesizesort);

 

                                Page<Todo> pageofTodo = todoService.findByUsername(usernamepageable);

 

                                List<Todo> getTodosList = pageofTodo.getContent();

                                todoResponse.setCurrentPage(page);

                                todoResponse.setTotalItems(pageofTodo.getTotalElements());

                                todoResponse.setTotalPages(pageofTodo.getTotalPages());

                                todoResponse.setSortField(sortField);

                 todoResponse.setSortDirection(sortDirection.equals("asc") ? "desc" : "asc");

                                todoResponse.setTodosList(getTodosList);

 

                                // Return Response

                                return todoResponse;

 

                }

 

 

Supporting  Classes:

public class TodoResponse implements Serializable{

       private static final long serialVersionUID = 1L;

 

       private int currentPage;

       private int totalPages;

       private long totalItems;

       private String sortField;

       private String sortDirection;

       private List<Todo> todosList;

☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝

@Entity

public class Todo {

       @Id

       @GeneratedValue(strategy=GenerationType.AUTO)

       private Long id;

       private String username;

       private String description;

       private Date targetDate;

       private boolean isDone;

✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌✌

 

 


No comments:

Post a Comment

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts