我有一篇带有惰性初始化字段评论的课程帖子:@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; }
1 回答
呼如林
TA贡献1798条经验 获得超3个赞
交易很可能是在这种方法上:
Post post = postService.getPostById(id);
然后你试试:
logger.info(post.getComments().size());
它在此时关闭的事务之外,此时Post
是一个分离的实体。
您的选择之一是使用注释控制器请求映射方法@Transactional(readOnly = true)
。
添加回答
举报
0/150
提交
取消