엔티티에서 데이터를 수정하는 메서드를 생성함으로써
값의 변경이 어디서 일어났는지 추적하기 용이해진다.
트랜잭션이 있는 서비스 계층에 식별자(id)와 데이터를 명확하게 전달하자
리팩토링 (feat. 파라미터 or DTO)
여러 문제점이 있겠지만
엔티티가 변경되었을 때 어느 시점에 변경되었는지 추적하기 어렵다는 문제가 있다.
이때 엔티티 클래스에 해당 값을 변경하는 메서드를 선언하면
메서드를 사용하는 위치를 파악하여
어느 시점에 그 값이 변경되는지 파악하는게 용이해진다.
public void modify(String title, String content){
setTitle(title);
setContent(content);
}
@Transactional(readOnly = false)
public void modifyNews(Long id, NewsForm newsForm){
News news = newsRepository.find(id);
news.modify(newsForm.getTitle(), newsForm.getContent());
}
Controller에서 form 객체를 파라미터로 넘기는 것 보다는
form객체 데이터를 넘기는게 더 좋다.
@PostMapping("/admin/news/modify/{newsId}")
public String modify(@PathVariable("newsId") Long id, NewsForm newsForm){
newsService.modifyNews(id, newsForm.getTitle(), newsForm.getContent());
return "redirect:/news/view/"+id;
}
@Transactional(readOnly = false)
public void modifyNews(Long id, String title, String content){
News news = newsRepository.find(id);
news.modify(title, content);
}
Controller에서는 newForm을 넘겨주는 대신, newsForm.getTitle(), newsForm.getContent()를 넘겨주고
Service에서는 각각의 값을 String형 title과 content로 받아서
modify 메서드에 전달한다.
혹시나 나중에 넘겨줘야하는 파라미터 량이 많아지면,
newsService.modifyNews(id, newsForm.getTitle(), newsForm.getContent());
이런식으로 넘겨줄 때 가독성을 해칠 수도 있다.
따라서, 이번에는 UpdateNewsDto를 만들어서 파라미터를 넘겨줌으로써 가독성과 유지보수성을 살린다.
@Getter @Setter
public class UpdateNewsDto {
private String title;
private String content;
}
@PostMapping("/admin/news/modify/{newsId}")
public String modify(@PathVariable("newsId") Long id, NewsForm newsForm){
UpdateNewsDto updateNewsDto = new UpdateNewsDto();
updateNewsDto.setTitle(newsForm.getTitle());
updateNewsDto.setContent(newsForm.getContent());
newsService.modifyNews(id,updateNewsDto);
return "redirect:/news/view/"+id;
}
@Transactional(readOnly = false)
public void modifyNews(Long id, UpdateNewsDto updateNewsDto){
News news = newsRepository.find(id);
news.modify(updateNewsDto);
}
public void modify(UpdateNewsDto updateNewsDto){
setTitle(updateNewsDto.getTitle());
setContent(updateNewsDto.getContent());
}
이로써 파라미터가 많을 때 유지보수하기 좋은 방법을 알아봤다.