我注意到一个奇怪的问题。我得到了这个异常(exception):
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.javacms.entity.Article.comments, could not initialize proxy - no Session
使用此代码:
@Override
@Transactional
public List<Comment> getCommentsFromArticle(int articleId) {
Article article = getArticle(articleId);
System.out.println(article);
List<Comment> comments = article.getComments();
//System.out.println(comments);
return comments;
}
但是当我从 System.out.println(comments) 中删除注释时,代码如下所示:
@Override
@Transactional
public List<Comment> getCommentsFromArticle(int articleId) {
Article article = getArticle(articleId);
System.out.println(article);
List<Comment> comments = article.getComments();
System.out.println(comments);
return comments;
}
代码工作正常,正如我怀疑的那样。有没有人有同样的问题。我不明白为什么我不使用 sysout 时会出现错误。
最佳答案
当您调用 article.getComments() 时,hibernate 将返回代理对象。除非你真的对评论执行任何操作,否则 hibernate 不会初始化它。 当您在注释上调用 system.println 时,toString() 将在对象上被调用,hibernate 会知道您正在对该对象执行操作,因此它将在它在事务中运行时对其进行初始化。 您可以明确调用 hibernate.initialize(comments) 。它会很好地工作
关于java - 仅在不使用 sysout 时才延迟初始化角色集合失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51106499/