java - 仅在不使用 sysout 时才延迟初始化角色集合失败

标签 java spring hibernate

我注意到一个奇怪的问题。我得到了这个异常(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/

相关文章:

json - Spring MVC + AngularJS 415 不支持的媒体类型

java - 当 i++ 操作的值发生并存储在它在 Java 中的引用中时..?

java - 如何在 Vaadin 14 中为选项卡设置不同的内容?

java - JAXB 使 Objectfactory 中的 QName 可访问

java - 在 JUnit 中比较两个 Hibernate session 是否相同

java - ORA-00932 : inconsistent datatypes: expected DATE got BINARY in Hibernate

spring - Hibernate Search..访问一个没有被密封的密封工作队列

java - 停留在比较器<T>

java.lang.NoClassDefFoundError : org/springframework/core/io/ResourceLoader 错误

java - 在 Spring batch 中查询批处理作业元数据