在处理OneToMany关系时如何在Hibernate中正确管理会话?

时间:2018-08-12 21:01:58

标签: java hibernate hibernate-session

我有两个具有OneToMany关系的类:

Post.java:

@OneToMany(mappedBy = "post")
private List<Comment> comments;

Comment.java:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "idPost")
private Post post; 

我正在尝试在某些日期之后发布带有其评论的帖子。这是我的方法:

@Override
public List<Post> findPostsWithCommentsAfterYesterday() {
    List<Post> result = new ArrayList<>();
    try {
        session.getCurrentSession().beginTransaction();
         Criteria criteria = session.getCurrentSession().createCriteria(Post.class);
        result = (List<Post>) criteria.createAlias("comments", "cms")
                .add(Restrictions.gt("cms.date", yesterday)).list();
        session.getCurrentSession().getTransaction().commit(); 
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    //
    return result;
}

列表返回相应的注释,但有以下例外:

 org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.farouk.Post.comments, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:249)
at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:45)
at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
at org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)

没有会话或会话已关闭?

我知道我正在关闭会话,但是在获得列表之后。

那么处理这种情况的最佳实践是什么?

1 个答案:

答案 0 :(得分:0)

我在this answer中找到了解决方案。这是因为默认情况下集合使用延迟加载,因此我必须更改为EAGER才能获取所有注释。