将请求dto和响应dto合并为一个dto

时间:2019-04-30 11:03:07

标签: spring dto

我注意到,很多时候我需要一个单独的DTO来处理请求和响应,因为请求增加了验证约束,并且响应通常包含更多数据。

例如:

package be.ambrassade.jeugdlink.model.request;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class AnswerRequest {
    @Size(min = 10, max = 1000)
    @NotNull
    private String message;


    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

并且:

package be.ambrassade.jeugdlink.model.response;

import java.sql.Timestamp;

public class AnswerResponse  {
    private int id;
    private String message;
    private UserResponse user;
    private Timestamp postedOn;
    private boolean chosen;
    private Short likes;
    private boolean userLikedAnswer;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public UserResponse getUser() {
        return user;
    }

    public void setUser(UserResponse user) {
        this.user = user;
    }

    public Timestamp getPostedOn() {
        return postedOn;
    }

    public void setPostedOn(Timestamp postedOn) {
        this.postedOn = postedOn;
    }

    public boolean isChosen() {
        return chosen;
    }

    public void setChosen(boolean chosen) {
        this.chosen = chosen;
    }

    public Short getLikes() {
        return likes;
    }

    public void setLikes(Short likes) {
        this.likes = likes;
    }

    public boolean isUserLikedAnswer() {
        return userLikedAnswer;
    }

    public void setUserLikedAnswer(boolean userLikedAnswer) {
        this.userLikedAnswer = userLikedAnswer;
    }
}

是否有任何方法可以将它们组合在一个通用的DTO for Answers中,也许以一种或另一种方式进行验证和属性过滤?我必须补充一点,数据库层会生成大量数据,例如id,postedOn时间戳等。

1 个答案:

答案 0 :(得分:0)

我通常要做的是拥有通用的请求和响应DTO,同时根据业务模型保留实体对象。这种方法的示例ResponseDTO如下所示。

public class ResponseDTO {

//SUCCESS / FAILURE
private String status;
//failure message if any
private String message;

//response pay load. eg. AnswerDTO
private Object payload;


}