spring.jpa.open_in_view 설정 : 커넥션을 언제 반납할지를 결정하는 설정
@Entiy
public class Post {
@Id
Long id;
String title;
@OneToMany(fetch = FetchType.LAZY)
Set<Voter> voters;
}
<div th:text="${post.id}"></div>
<div th:text="${post.title}"></div>
<div th:text="${#sets.size(post.voters)}"></div>
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
public Post getPostDetail(Long id) {
Post post = postRepository.findById(id);
return post;
}
}
public class PostDetailDto {
Long id;
String title;
Set<Voter> voters = new HashSet<Voter>;
public void addVoter(Voter voter) {
voters.add(voter);
}
}
PostDetailDto타입의 getPostDetail() 메소드 추가
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
public Post getPostDetail(Long id) {
Post post = postRepository.findById(id);
return post;
}
public PostDetailDto getPostDetail(Long id) {
Post post = postRepository.findById(id);
PostDetailDto dto = new PostDetailDto();
dto.setId(post.getId());
dto.setTitle(post.getTitle());
for (Voter voter : post.getVoters()) {
dto.addVoter(voter);
}
return dto;
}
}
JPA를 사용할 경우, 이와 같이
Entity에 있는 데이터를 DTO에 담는 코드 작성이 매우 빈번함