๐ ๊ณต๋ถํ๊ฒ ๋ ๊ณ๊ธฐ
QNA ํ๋ก์ ํธ๋ฅผ ๊ณต๋ถํ๋ฉด์ DTO ๋ฅผ ๋ง์ด ํ์ฉํด๋ณด๋ ค๊ณ ํ๋๋ฐ, ๋ต๋ณ ์ ์ฅ ๊ณผ์ ์์ ์ ๋ ฅ๋ฐ์ ๋ฐ์ดํฐ๋ฅผ DTO ํํ๋ก ์ ์ฅํ๋ ๊ฒ ๊น์ง๋ ์ ๋ฒ์ ์ ๋ฆฌํ Entity ๋ฅผ DTO ํํ๋ก ๋ฐ๊พธ๋ ๊ฒ๊ณผ ๋น์ทํ๊ฒ ํ ์ ์์๋ค.
๊ทธ๋ฐ๋ฐ AnswerRepository ๋ก save ๋ฅผ ์ํํ๋ ค๋ฉด ์ธ์๊ฐ ๋๋ ๊ฐ์ฒด๊ฐ Answer ์ด์ด์ผํ๋๋ฐ ํํ ๋ฐ์ดํฐ ๊ฐ์ฒด๋ DTO ์๋ค. ๋ฌผ๋ก ๊ท์ฐฎ๊ฒ Answer ๊ฐ์ฒด๋ฅผ ์์ฑ ํ ํ๋ํ๋ ๋ด์์ ๋ง๋ค์ด๋ผ ์ ์๊ฒ ์ง๋ง ๋ถ๋ช ํ ๋ฐฉ๋ฒ์ด ์๊ฒ ์ง๋ผ๊ณ ์๊ฐํ์๋ค.
๊ฒ์์ฐฝ์ "Spring DTO to Entity" ๋ผ๊ณ ๊ฒ์์ ํ๋ ModelMapper ๋ฅผ ํตํ ๋ฐฉ์์ด ๋์์์๋ค. ํด๋น ๋ฐฉ๋ฒ์ ์ ๋ฒ์ Entity to DTO ๋ฅผ ํ๋ฉด์๋ ๊ถ๊ธํ๋ ๋ฐฉ์์ด๋ผ ๊ณผ์ ์ ์ ๋ฆฌํด๋ณด๊ธฐ๋ก ํ๋ค.
์ฐธ๊ณ : https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
1๏ธโฃ ModelMapper ์์กด์ฑ ์ฃผ์ ๋ฐ Bean ๋ฑ๋ก
dependencies {
// modelMapper ์์กด์ฑ ์ถ๊ฐ
implementation group: 'org.modelmapper', name: 'modelmapper', version: '3.1.0'
}
@Configuration // Bean ๋ฑ๋ก์ ์ํ ์ค์ ํ์ผ์์ ๋ช
์
public class AppConfig {
@Bean
public ModelMapper modelMapper() { // ModelMapper Bean ๋ฑ๋ก
return new ModelMapper();
}
}
@Configuration ์ด๋ ธํ ์ด์ ์ด ์์ด์ผ SpringBoot ์์ ์คํ ์ ์ Bean ํ์์ด ๊ฐ๋ฅํ๋ค.
2๏ธโฃ DTO ์์ฑ
public class AnswerDto {
@Setter
@Getter
public static class addAnswer {
private String content;
private LocalDateTime createDate;
private Question question;
public addAnswer (String content, Question question) { // ์์ฑ์
this.content = content;
this.question = question;
this.createDate = LocalDateTime.now();
}
}
}
์ถํ ๊ฐ์ ์ ์ฅํ๊ณ , ๊ฐ์ ธ์ค๋ ๊ณผ์ ๋ค์ด ํ์ํ๊ธฐ ๋๋ฌธ์ Getter ์ Setter ๋ ๋ฐ๋์ ์์ด์ผํ๋ค.
3๏ธโฃ Controller ๋จ
public class AnswerController {
// (์๋ต)
@PostMapping("/create/{id}")
@ResponseBody
public String createAnswer(@PathVariable int id, @RequestParam (defaultValue = "") String content) {
// (์๋ต)
answerService.createAnswer(id,content);
return "๋ต๋ณ์ด ๋ฑ๋ก๋์์ต๋๋ค.";
}
}
4๏ธโฃ Service ๋จ
public class AnswerService {
private final AnswerRepository answerRepository;
private final QuestionRepository questionRepository;
private final ModelMapper modelMapper;
public void createAnswer(int id, String content) {
// (์๋ต)
addAnswer addAnswer = new addAnswer(content, question);
Answer answer = modelMapper.map(addAnswer, Answer.class); // Mapper ์ฌ์ฉ ๋ถ๋ถ
answerRepository.save(answer); // Answer ๊ฐ์ฒด ๋๊ฒจ์ค
}
}
Controller ๋ก ๋ถํฐ ๋๊ฒจ๋ฐ์ ๊ฐ๋ค์ ๋ฐํ์ผ๋ก addAnswer DTO ๋ฅผ ์์ฑํ๊ณ , ModelMapper ๋ฅผ ํตํด ๊ฐ์ ์์ฑ๋ค์ ์ฐ๊ฒฐ์์ผ Answer ๊ฐ์ฒด๋ฅผ ์์ฑํ ํ Repository ๋ฅผ ํตํด ๊ฐ์ ์ ์ฅํ๋ค. ๋ง์ฝ ModelMapper ๋ฅผ ์ฐ์ง ์์๋ค๋ฉด ์๋์ ๊ฐ์ด ๊ท์ฐฎ์ ๊ณผ์ ์ ๊ฑฐ์ณ์ผํ์ ๊ฒ์ด๋ค.
Answer answer = new Answer(addAnswer.getContent, addAnswer.getCreateDate, ... )
๊ฐ๋ ์ฑ๋ ๋์์ง๊ณ , ํน์๋ํ๋ ์ค์๋ ์ค์ฌ์ค ์ ์๋
5๏ธโฃ ๊ฒฐ๊ณผ ํ์ธ

์๋ง์ธ ๋งคํ๋์ด ๊ฐ์ด ์ ์ฅ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.