Spring Boot JPA - Pagination

Pagination 

Pagination is a mechanism to separate a bit result set into smaller chunks. Providing a fluent pagination navigator could increase both the value of your website for search engines and enhance user experience through minimizing the response time. 

Static pagination with Spring Boot 

Let's first define ExampleEntity and a repository for ExampleEntity


@Entity
@Table(name = "Example")
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ExampleEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(length = 100, nullable = false)
private String content;
}



@Repository
public interface ExampleRepository extends JpaRepository<ExampleEntity, Long> {

}


Now's let's insert dummy data's that will be used for pagination. 


@Test
public void testInsert() {
LongStream.rangeClosed(1, 300).forEach(i -> {
ExampleEntity exampleEntity = ExampleEntity.builder()
.id(i)
.content("Content " + i)
.build();

exampleRepository.save(exampleEntity);
});
}


Let's check whether the data has been inserted correctly

Inserted dummy data
So, let's see how Spring provides pagination. We'll use org.springframework.data.domain.Pageable interface which is an abstract interface for pagination information. Since Pageable is an interface, we cannot make an instance directly. Instead we'll use PageRequest class to create an instance. Since PageRequest class constructor's access specifier is protected, we cannot directly use the constructor, instead we'll use of() to retrieve the instance. 


@Test
public void testPagenation() {

Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());

Page<ExampleEntity> page = exampleRepository.findAll(pageable);

System.out.println("Total pages: " + page.getTotalPages());
System.out.println("Total count: " + page.getTotalElements());
System.out.println("Current page number: " + page.getNumber());
System.out.println("Page size: " + page.getSize());
System.out.println("Has next page?: " + page.hasNext());
System.out.println("Is first page?: " + page.isFirst());

for (ExampleEntity e : page.getContent()) {
System.out.println(e);
}
}


Let's look at the result 

Result of pagination

REFERENCE 

https://dzone.com/articles/pagination

Comments

Popular posts from this blog

Structures of JAVA

What is URI(URN, URL)

Java Data Structures VS Python, C/C++ Data Structures

Spring Boot JPA - What is JPA, Entity, Repository

Design Pattern - Proxy