How to returnDTO instead of entity in Spring boot pagination?

Tags: ,



My DTO is different from entity. How can I return a DTO instead of entity with pagination while still showing information of all pages?

Controller:

@GetMapping("/{name}")
public Page<Student> getStudent(@PathVariable(value = "name") String name, Pageable pageable){
     Page <Student> page = studentService.getStudent(name, pageable);
     return page;
}

Service:

public Page<Student> getStudent(String name, Pageable pageable){
    Page<Student> students = studentRepository.findAllByName(name, pageable);
    return students;
}

Repository:

@Repository
public interface StudentRepository extends 
    PagingAndSortingRepository<Student, Long> {
    Page<Student> findAllByName(String name, Pageable pageable);
}

DTO:

@Data
public class StudentDTO extends ResourceSupport {
   Long _id;
   String name;
}

Entity:

@Entity
@Data
@NoArgsConstructor(force = true, access = AccessLevel.PUBLIC)
public class Student {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private Long grade;
}

Answer

The StudentDTO class can have a constructor with a Student parameter.

public StudentDTO(Student student) {
    this._id = student.getId();
    this.name = student.getName();
}

Then you can call map on the Page object.

Page<StudentDTO> dtoPage = page.map(student -> new StudentDTO(student));


Source: stackoverflow