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 |
@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 |
Comments
Post a Comment