没有Lazy对象的休眠列表

时间:2015-12-22 05:18:08

标签: java hibernate lazy-loading

我最近使用的是Hibernate,并且需要显示以注释为外键(@OneToMany)的主题,如下所示:

Topic.class

...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "topic")
public Set<Comment> getComments() {
    return this.communityComments;
}

...

我使用Hibernate Tools生成包含以下内容的DAO:

public List findByExample(Topic instance) {
    try {
        List results = sessionFactory.getCurrentSession()
                .createCriteria("com.some.models.Topic").add(Example.create(instance))
                .list();
        return results;
    } catch (RuntimeException re) {
        throw re;
    }
}

当我使用findByExample获取主题时,将返回一组主题。问题是我如何迭代集合?当我执行以下代码时:

Set<Topic> oriList = topicDAO.findByExample(OneExample);
Iterator<Topic> it = oriList.iterator();

它显示了没有会话&#39;例外。原因是我认为oriList.iterator()试图访问惰性对象 - 评论。

有没有办法以最小的变化解决这个问题?

或者有没有办法在不使用迭代器的情况下将所有注释设置为null

1 个答案:

答案 0 :(得分:0)

这里的问题在于获取会话。

您应该尝试 openSession 而不是 getCurrentSession

public List findByExample(Topic instance) {
    try {
        List results = sessionFactory.openSession()
                .createCriteria("com.some.models.Topic").add(Example.create(instance))
                .list();
        return results;
    } catch (RuntimeException re) {
        throw re;
    }
}