我有一篇带有惰性初始化字段评论的课程帖子:
@Entity
@Table(name = "POSTS")
public class Post {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "post_id",
unique = true, nullable = false)
@JsonView(Views.Public.class)
private Integer postId;
@Column(name = "POST_BODY", columnDefinition = "text")
@JsonView(Views.Public.class)
private String postBody;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "USERNAME")
private User user;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "post", fetch = FetchType.LAZY)
private Set<PostComment> comments = new HashSet<>();
}
正如我从 hibernate 文档中了解到的那样,如果由于延迟初始化而未初始化某些内容,如果您随后调用它的 getter 方法,它应该被初始化,但是当我收到我的帖子并尝试调用 getter 方法进行评论时,我得到一个异常。
@GetMapping(path = {"/post/{id}"})
public ModelAndView showSpecificPost(@PathVariable(value = "id") Integer id) {
User currentUser = userService.findByUserName(auth.getName());
Post post = postService.getPostById(id);
logger.info(post.getComments().size());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("postTemplates/specificPost");
return modelAndView;
}
呼如林
相关分类