Dto, Entity 매핑 시 빌더를 효율적으로 사용하는 방법
2분 소요
SpringBoot : 2.7.5 Java : 11
개요
Request에서 Dto로, Entity에서 Dto로의 변환입니다.
Java로 개발하다 보면 같은 데이터가 여러 클래스를 거쳐 전달되고 받아집니다. JPA로 DB에서 데이터를 가져온다면 기본적으로 Entity, Dto, Request/Response 세 가지 정도의 클래스를 사용하게 됩니다.
DB에서 Entity 클래스를 가져오고, 서비스 계층에서 Entity를 Dto로 변환한 뒤, 마지막으로 Dto를 Response로 변환해 반환합니다. 저장도 비슷하게 req → dto → entity 순서입니다.
여러분은 이런 변환을 어떤 방식으로 하는 것을 선호하시나요? 방법은 여러 가지가 있지만, 저는 주로 빌더 패턴을 좋아하고 선호합니다.
하지만 이 방식도 변경에는 다소 취약합니다. 간단한 예제로 시작해 보겠습니다.
클래스 (Entity, Dto, Res)
Entity를 Dto로 변환하는 과정만 설명하겠습니다. 다른 변환도 같은 방식으로 매핑되기 때문입니다.
public class PostEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long postSeq;
@Column(name = "POST_TITLE")
private String postTitle;
@Column(name = "POST_CONTENT")
private String postContent;
@Column(name = "CREATE_DATE")
private Date createDate;
}
@Getter
@Builder
@RequiredArgsConstructor
public class PostDto {
private final Long postSeq;
private final String postTitle;
private final String postContent;
private final Date createDate;
}
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
@Transactional(readOnly = true)
public PostDto findPostById(long postSeq) throws Exception {
final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
-> new NoSuchElementException("cannot found post info with id : " + postSeq));
return PostDto.builder()
.postSeq(post.getPostSeq())
.postTitle(post.getPostTitle())
.postContent(post.getPostContent())
.createDate(post.getCreateDate())
.build();
}
}
Builder 패턴을 사용하면 이런 식으로 Entity를 Dto로 변환하게 됩니다.
하지만 한번 생각해 봅시다. PostEntity에 컬럼이 하나 추가되면 어떻게 될까요?
@Column(name = "CREATE_BY")
private String createBy;
여러 가지 작업을 해야 합니다.
- Dto에 같은 컬럼 추가
- 빌더를 사용하는 모든 곳에 새 컬럼 추가
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
@Transactional(readOnly = true)
public PostDto findPostById(long postSeq) throws Exception {
final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
-> new NoSuchElementException("cannot found post info with id : " + postSeq));
return PostDto.builder()
~~~
.createBy(post.getCreateBy())
.build();
}
}
여기서 문제가 생깁니다. 메서드를 몇 개나 수정해야 할까요? 어디에서 사용했을까요?
이 문제를 해결하기 위해 Entity를 Dto로 변환할 때 static 메서드를 사용할 수 있습니다.
@Getter
@Builder
@RequiredArgsConstructor
public class PostDto {
private final Long postSeq;
private final String postTitle;
private final String postContent;
private final Date createDate;
private String createBy;
public static PostDto ofEntity(PostEntity entity) {
return PostDto.builder()
.postSeq(entity.getPostSeq())
.postTitle(entity.getPostTitle())
.postContent(entity.getPostContent())
.createDate(entity.getCreateDate())
.createBy(entity.getCreateBy()).build();
}
}
Dto에 of 메서드를 static으로 선언하고, 서비스에서 Entity를 Dto로 변환할 때 이 메서드를 사용하면 됩니다.
@Transactional(readOnly = true)
public PostDto findPostById(long postSeq) throws Exception {
final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
-> new NoSuchElementException("cannot found post info with id : " + postSeq));
return PostDto.ofEntity(post);
}
이 경우 앞과 같은 상황에서도 Dto의 static 메서드에 새 컬럼만 추가하면 됩니다.
리스트를 변환할 때도 더 효율적입니다.
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
@Transactional(readOnly = true)
public List<PostDto> findAllPost() throws Exception {
return postRepository.findAll().stream().map(PostDto::ofEntity)
.collect(Collectors.toList());
}
}
이 방법은 매우 간단하고 효율적입니다.