我有一篇帶有惰性初始化字段評(píng)論的課程帖子:@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 方法,它應(yīng)該被初始化,但是當(dāng)我收到我的帖子并嘗試調(diào)用 getter 方法進(jìn)行評(píng)論時(shí),我得到一個(gè)異常。@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貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
交易很可能是在這種方法上:
Post post = postService.getPostById(id);
然后你試試:
logger.info(post.getComments().size());
它在此時(shí)關(guān)閉的事務(wù)之外,此時(shí)Post
是一個(gè)分離的實(shí)體。
您的選擇之一是使用注釋控制器請(qǐng)求映射方法@Transactional(readOnly = true)
。
添加回答
舉報(bào)
0/150
提交
取消