Last active
February 10, 2021 11:52
-
-
Save ByungJun25/d52f7bcd6338724a323b8e8b899276b4 to your computer and use it in GitHub Desktop.
How to manage a DTO classes with Interface and Inner class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Entity | |
@Getter | |
public class Data { | |
private UUID id; | |
private String name; | |
private String value; | |
} | |
// DTO | |
public interface DataDTO { | |
enum Type { | |
RESPONSE1, RESPONSE2, RESPONSE3; | |
} | |
public static DataDTO of(Data data, Type type) { | |
DataDTO result = null; | |
switch (type) { | |
case RESPONSE1: | |
result = Response1.builder().id(data.getId()).name(data.getName()).value(data.getValue()).build(); | |
break; | |
case RESPONSE2: | |
result = Response2.builder().id(data.getId()).name(data.getName()).build(); | |
break; | |
case RESPONSE3: | |
result = Response3.builder().name(data.getName()).value().build(); | |
break; | |
default: | |
result = Default.builder().id(data.getId()).name(data.getName()).value(data.getValue()).build(); | |
break; | |
} | |
return result; | |
} | |
@Getter | |
@Builder | |
class Default implements DataDTO { | |
private final UUID id; | |
private final String name; | |
private final String value; | |
} | |
@Getter | |
@NoArgsConstructor | |
class Request implements DataDTO { | |
private String name; | |
private String value; | |
} | |
@Getter | |
@Builder | |
class Response1 implements DataDTO { | |
private final UUID id; | |
private final String name; | |
private final String value; | |
} | |
@Getter | |
@Builder | |
class Response2 implements DataDTO { | |
private final UUID id; | |
private final String name; | |
} | |
@Getter | |
@Builder | |
class Response3 implements DataDTO { | |
private final String name; | |
private final String value; | |
} | |
} | |
// RestController | |
@RequiredArgsConstructor | |
@RequestMapping("/datas") | |
@RestController | |
public class Controller { | |
private final DataService dataService; | |
@GetMapping | |
public ResponseEntity<List<DataDTO>> getMethod() { | |
List<Data> datas = this.dataService.getAllDatas(); | |
List<DataDTO> dtos = datas.stream().map(d -> DataDTO.of(d, DataDTO.Type.RESPONSE2)).collect(Collectors.toList()); | |
return ResponseEntity.ok().body(dtos); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment