如何为 Page<> 接口创建 DTO?

How do I make a DTO for the Page<> interface?

我正在使用 Spring Boot (MVC) 和 Hiberbate 编写在线商店。问题是当我得到一份饮料清单时,JSON 从 Page 界面给我一些不必要的信息。我不知道如何为 interfaces 创建 DTO 来删除这些字段。这种情况我该怎么办。有人可以有现成的解决方案吗?

    public Page<DrinkDTO> getAllDrinks(int page, int pageSize) {

        PageRequest pageRequest = PageRequest.of(page, pageSize, Sort.by("id"));

        final Page<Drink> drinks = drinkRepository.findAll(pageRequest);

        return drinkMapper.drinksToDrinksDTO(drinks);
    }

我使用本机查询,然后我大部分时间都做 dto 预测。

这里是一个DTO投影的例子

public interface OvertimeRequestView {
public Long getId();

public String getEmployeeFirstName();

public String getEmployeeLastName();

public Long getOvertimeHours();

public Date getOvertimeDate();

public String getDescription();

public String getStatus();

public String getApproverName();

public default String getEmployeeFullName() {
    String lastName = this.getEmployeeLastName();
    String firstName = this.getEmployeeFirstName();
    if (null != firstName) {
        return firstName.concat(" ").concat(lastName);
    }
    return lastName;
}

}

这里是带有本机查询的存储库。请注意,由于查询 returns 'id' 列我在上面的 dto 中有一个 getId() 方法,并且因为它有 employeeFirstName 我在 dto 中有 getEmployeeFirstName() 等等。另请注意,我包含一个计数查询,没有计数查询,查询有时会失败,尤其是当查询很复杂且包含连接时

@Query(value = "select ovr.id,\n" +
        "       u.first_name       as employeeFirstName,\n" +
        "       u.last_name        as employeeLastName,\n" +
        "       ovr.overtime_date  as overtimeDate,\n" +
        "       ovr.description  as description,\n" +
        "       ovr.overtime_hours as overtimeHours\n" +
        "from overtime_requests  ovr\n" +
        "         left join employees e on ovr.employee_id = e.id\n" +
        "         left join users u on e.user_id = u.id",
        nativeQuery = true,
        countQuery = "select count(ovr.id)\n" +
                "from overtime_requests  ovr\n" +
                "         left join employees e on ovr.employee_id = e.id\n" +
                "         left join users u on e.user_id = u.id")
public Page<OvertimeRequestView> getAllActive(Pageable pageable);

更多内容可以查看spring data documentation

@Data
@AllArgsConstructor
public class CustomPage {

    Long totalElements;

    int totalPages;

    int number;

    int size;
}
@Data
public class PageDTO<T> {

    List<T> content;

    CustomPage customPage;

    public PageDTO(Page<T> page) {
        this.content = page.getContent();
        this.customPage = new CustomPage(page.getTotalElements(),
                page.getTotalPages(), page.getNumber(), page.getSize());
    }

例如服务:

public PageDTO<DrinkDTO> getAllDrinks(int page, int pageSize) {

        PageRequest pageRequest = PageRequest.of(page, pageSize, Sort.by("id"));

        final Page<Drink> drinks = drinkRepository.findAll(pageRequest);

        return new PageDTO<DrinkDTO>(drinkMapper.drinksToDrinksDTO(drinks));
    }