简体   繁体   中英

Ignore specific properties conditionally DTO

I have a specific requirement, I have a single POJO like EmployeeDTO.java

with below Fields;

int employeeId;
String Name;
double salary;
String createdBy;
Date createdTimestamp;
String updatedBy;
Date updatedTimestamp; 

Now my reqirement is while I will get a Create API request as a JOSN I shouldn't get any fields like employeeId, createdBy, createdTimestamp, updatedBy, updatedTimestamp.

But in a GET API response, I should send all these fields.

I can't use jsonIgnore here as for a field like employeeId I am not expcting it in the request, but I want to send it in the response.

In a PATCH/PUT api call I am expecting employeeId from UI in the request but not below 4 fields createdBy, createdTimestamp, updatedBy, updatedTimestamp.

So a simple solutions can be I can create separate DTOs, like EmployeeDTO, EmployeeCreateRequestDTO, EmployeeUpdateRequestDTO. But it will leads to duplication of codes.

Is there any better way or json feature/annotation is available to achieve this ?

The reason I want this, In the Swagger Model Schema it is displaying all the fields available in EmplyeeDTO, I want to be specific here for a Create request A user should not see any of the the fields which are getting set in back end like id, createdBy etc.

Using specific classes that represent clearly the data/behavior of the business use case is better (in terms of readability, maintainability) than mixing things that should not be.

So a simple solutions can be I can create separate DTOs, like EmployeeDTO, EmployeeCreateRequestDTO, EmployeeUpdateRequestDTO. But it will leads to duplication of codes.

It will not create necessarily code duplication if all common fields to EmployeeCreateRequestDTO and EmployeeUpdateRequestDTO are present only in EmployeeDTO .

To avoid the duplication, you have two ways.

1) Inheritancy
EmployeeCreateRequestDTO and EmployeeUpdateRequestDTO are subclasses of EmployeeDTO .
Advantage : subclasses have a direct access to the public common getters/setters of the EmployeeDTO parent

2) Composition
Each one of these specific classes wraps a EmployeeDTO instance and define their own fields.
Advantage : subclasses have more flexibility to define which should be accessible from the EmployeeDTO field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM