簡體   English   中英

調用getter到惰性初始化字段后的org.hibernate.lazyinitializationexception

[英]org.hibernate.lazyinitializationexception after calling getter to a lazy initialised field

我有一堂課帖子,上面有一個懶惰的init字段評論:

@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<>();
}

正如我從休眠文檔中了解到的那樣,如果由於延遲初始化而未初始化某些內容,則應調用它的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;
    }

事務最有可能使用此方法:

Post post = postService.getPostById(id);

然后,您嘗試:

logger.info(post.getComments().size());

在此時關閉的交易之外,而Post是此時的獨立實體。

您的選擇之一是使用@Transactional(readOnly = true)注釋控制器請求映射方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM