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

huangapple go评论29阅读模式
英文:

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

问题

我正在使用Spring Boot(MVC)和Hibernate编写一个在线商店。问题是,当我获取饮料列表时,JSON会给我返回Page接口中不必要的信息。我不知道如何为这些接口创建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);
}
英文:

I am writing an online store using Spring Boot (MVC) and Hiberbate. The problem is that when I get a list of drinks, JSON gives me unnecessary information from the Page interface. I don't know how you can create an DTO for the interfaces to get rid of these fields. What should I do in this situation. Can someone have a ready-made solution?

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

    public Page&lt;DrinkDTO&gt; getAllDrinks(int page, int pageSize) {

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

        final Page&lt;Drink&gt; drinks = drinkRepository.findAll(pageRequest);

        return drinkMapper.drinksToDrinksDTO(drinks);
    }

答案1

得分: 1

@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());
    }
}

Service for example:
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));
}
英文:
@Data
@AllArgsConstructor
public class CustomPage {

    Long totalElements;

    int totalPages;

    int number;

    int size;
}
@Data
public class PageDTO&lt;T&gt; {

    List&lt;T&gt; content;

    CustomPage customPage;

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

Service for example:

public PageDTO&lt;DrinkDTO&gt; getAllDrinks(int page, int pageSize) {

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

        final Page&lt;Drink&gt; drinks = drinkRepository.findAll(pageRequest);

        return new PageDTO&lt;DrinkDTO&gt;(drinkMapper.drinksToDrinksDTO(drinks));
    }

答案2

得分: -1

我使用原生查询,然后大多数时候进行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;
    }
}

这是带有原生查询的存储库。请注意,由于查询返回'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

英文:

I use native query and then I i do dto projections most of the time.

Here is an example of DTO projection

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(&quot; &quot;).concat(lastName);
    }
    return lastName;
}

}

and here is the repository with a native query. notice that since the query returns 'id' column I have a getId() method in the dto above,and since it has employeeFirstName i have getEmployeeFirstName() in the dto and so on. Notice also that I include a count query, without a count query, the queries sometime fail especially if the queries are complex and contain joins

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

For more you can check from spring data documentation

huangapple
  • 本文由 发表于 2020年7月30日 23:18:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63176297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定