亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

org.hibernate.lazyinitializationexception 在調用

org.hibernate.lazyinitializationexception 在調用

猛跑小豬 2022-12-21 16:40:59
我有一篇帶有惰性初始化字段評論的課程帖子:@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)。


查看完整回答
反對 回復 2022-12-21
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號