我有一篇帶有惰性初始化字段評論的課程帖子:@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 文檔中了解到的那樣,如果由于延遲初始化而未初始化某些內(nèi)容,如果您隨后調(diào)用它的 getter 方法,它應該被初始化,但是當我收到我的帖子并嘗試調(diào)用 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條經(jīng)驗 獲得超3個贊
交易很可能是在這種方法上:
Post post = postService.getPostById(id);
然后你試試:
logger.info(post.getComments().size());
它在此時關(guān)閉的事務之外,此時Post
是一個分離的實體。
您的選擇之一是使用注釋控制器請求映射方法@Transactional(readOnly = true)
。
添加回答
舉報
0/150
提交
取消