3

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;
}
Feedforward
  • 4,521
  • 4
  • 22
  • 34
Chefk5
  • 456
  • 6
  • 14

4 Answers4

9

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));
TomVW
  • 1,510
  • 13
  • 26
1

Please look here - this is an approach of how to work with DTO in Spring Data REST projects

1

You can do as follows:

 @Query("SELECT new StudentDTO(student.id, student.name) FROM Student student "
            + "WHERE student.name like :name ")
    List<StudentDTO> findAllCustomBy(@Param("name") String name)

and then you create a Constructor inside StudentDto

   public class StudentDto {
        public StudentDto(Long id, String name){
          this.id = id;
          this.name = name;
        }
Guilherme Alencar
  • 1,243
  • 12
  • 21
0
Pageable pageable = PageRequest.of(pageNo,PAGE_SIZE_12);
Page<StudentDTO> studentDTO = new PageImpl<>(studentDTO ,pageable,studentDTO.size());
Rajesh Bhushan
  • 61
  • 1
  • 1
  • 12
  • 4
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Sep 28 '20 at 14:55