Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Service Layer에서 도메인 객체가 아닌 DTO를 반환해야하는 이유? (feat.Open Session In View) #26

Open
NewWisdom opened this issue May 17, 2021 · 0 comments
Labels
atdd-subway-map 지하철 노선도 관리 SpringBoot 스프링

Comments

@NewWisdom
Copy link
Owner

NewWisdom commented May 17, 2021

Open Session In View?

View 단에서 Session(영속성 컨텍스트)을 여는 것에 대한 설정을 의미한다.
만약 컨트롤러 단에서 DTO내에서 도메인을 받아 DTO를 만들 경우, 아래와 같은 상황을 살펴본다.

@GetMapping("/api/members/{id}")
public ResponseEntity<MemberResponse> getMemberWithPosts(@PathVariable Long id) {
    Member member = memberService.findPostsByMemberId(id);

    return ResponseEntity.ok(MemberResponse.of(member));
}

// ... 

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class PostResponse {
    private Long id;
    private String content;

    public static List<PostResponse> of(List<Post> posts) {
        return posts.stream()
            .map(post -> new PostResponse(post.getId(), post.getContent()))
            .collect(Collectors.toList());
    }
}

이 부분은 JPA를 사용하여 지연 로딩된 객체를 초기화하는 것인데,
이는 영속성 컨텍스트의 도움을 받아서 이루어진다.
하지만 서비스 계층에서 @transaction 이 걸려있을 경우 서비스 레이어가 종료되는 시점에 Transaction이 닫힌다.

때문에 컨트롤러 계층은 영속성 컨텍스트가 닫힌 상태인데,
현재 DTO안에서 gertPost()를 통해 Post 객체를 초기화하고 있다.
이 경우 Open Session In View이 true일 경우 가능한데, 스프링 부트에서는 이 설정을 자동으로 True로 설정하기 때문이다.

그런데 이 Open Session In View 설정이 true가 아닐 경우, View인 컨트롤러에서 DTO를 만들 경우 문제가 생기게 된다.
스프링 부트에서는 이 설정이 되어있고 현 상황에서는 JPA를 사용하지도 않으니 문제될 것이 전혀 없지만,
후에 JPA를 사용하고, Open Session In View의 설정에 대해 생각해본다면 서비스 레이어에서 DTO를 반환하는 것이 조금 더 좋아보인다.

또한 화면에 필요한 데이터를 표현하기 위해 도메인 자체나 도메인의 getter를 노출시키는 것이 옳은 것인가도 생각해 볼 수 있다.

때문에 도메인의 정보를 외부(view)에 노출하는 경우, interface를 통해 제공하고, 이 구현체(DTO)를 뷰에 노출시키자.

TMI
image
피드백으로 서비스 레이어에서 도메인 객체가 아닌 DTO를 반환할 것을 제안(?)받았다.
그러면서 Open Session in View에 대한 내용도 가볍게 볼 것을 권유 받고 조금 정리해보았다.
사실 JPA를 잘 알지 못하는 상태에서 영속성 컨텍스트와 관련된 내용을 보니 완벽히 이해했다곤 할 수 없다.
그래도 지금은 이런 개념도 있구나 정도로 익히고.... 훗날 완벽히 이해 되겠지...
이를 살펴보면서 서비스 레이어에서 DTO까지 반환하는 이유를 알아보자.

참고자료

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
atdd-subway-map 지하철 노선도 관리 SpringBoot 스프링
Projects
Development

No branches or pull requests

1 participant