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

时间:2019-05-30 13:00:10

标签: java spring hibernate

我有一堂课帖子,上面有一个懒惰的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;
    }

1 个答案:

答案 0 :(得分:1)

最有可能使用此方法进行交易:

Post post = postService.getPostById(id);

然后尝试:

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

位于此时已关闭的事务之外,并且Post是此时的分离实体。

为您提供的一种选择是使用@Transactional(readOnly = true)注释控制器请求映射方法。