Java 只有在sysout未使用时,才能延迟初始化角色集合

Java 只有在sysout未使用时,才能延迟初始化角色集合,java,spring,hibernate,Java,Spring,Hibernate,我注意到一个奇怪的问题。我有一个例外: 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>

我注意到一个奇怪的问题。我有一个例外:

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;
}
@覆盖
@交易的
公共列表getCommentsFromArticle(int articleId){
Article=getArticle(articleId);
System.out.println(文章);
列表注释=article.getComments();
//System.out.println(注释);
返回评论;
}
但当我从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;
}
@覆盖
@交易的
公共列表getCommentsFromArticle(int articleId){
Article=getArticle(articleId);
System.out.println(文章);
列表注释=article.getComments();
System.out.println(注释);
返回评论;
}

代码运行良好,就像我怀疑的那样。有人有过同样的问题吗。我不明白为什么在我不使用sysout时会出现错误。

多亏了JB Nizet,我删除了一个错误。现在代码如下所示:

@Override
@Transactional
public List<Comment> getCommentsFromArticle(int articleId) {
    List<Comment> comments = new ArrayList<>(getArticle(articleId).getComments());
    return comments;
}
@覆盖
@交易的
公共列表getCommentsFromArticle(int articleId){
List comments=new ArrayList(getArticle(articleId).getComments());
返回评论;
}

调用article.getComments()时,hibernate将返回代理对象。除非您实际对注释执行任何操作,否则hibernate不会初始化它。 当您在comments上调用system.println时,toString()将在对象上被调用,hibernate将知道您正在该对象上执行操作,因此它将在事务中运行时对其进行初始化。
您可以显式地调用hibernate.initialize(注释)。它可以正常工作

,因为打印注释会在您在事务中且会话仍处于打开状态时初始化集合。如果没有它,集合将保持未初始化状态,当会话关闭时,尝试在事务外部对其进行初始化将无法工作。