Hej. Mam relacje @OneToMany
do @ManyToOne
Post do postComments. W obydwu encjach fetch
mam ustawiony na lazy. Mam metodę, która ma mi wyświetlić wszystkie komentarze z postu.
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
@Transactional
void printPostComments(Long postId) {
postRepository.findById(postId).stream()
.map(Post::getComments)
.flatMap(Set::stream)
.forEach(System.out::println);
}
}
Nie rozumiem tylko czemu przy wywołaniu tej metody dostaje wyjątek LazyInitializationException
. Jeśli dobrze rozumiem @Transactional
otwiera mi transakcje podczas wywołania metody i zamyka ją po jej zakończeniu. Więc gdy chce pobrać komentarze hibernate powinien mieć jeszcze możliwość odpytania o komentarze?
Załączam jeszcze encje:
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@Builder.Default
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<PostComment> comments = new HashSet<>();
public void addComment(PostComment newComment) {
comments.add(newComment);
newComment.setPost(this);
}
public void removeComment(PostComment newComment) {
comments.remove(newComment);
newComment.setPost(null);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return Objects.equals(id, post.id);
}
@Override
public int hashCode() {
return 0;
}
}
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PostComment that = (PostComment) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return "PostComment{" +
"review='" + review + '\'' +
'}';
}
}
99xmarcin99xmarcin