Java 无惰性对象的休眠列表
我最近正在使用Hibernate,需要显示以注释作为外键(@OneToMany)的主题,如下所示: 主题类Java 无惰性对象的休眠列表,java,hibernate,lazy-loading,Java,Hibernate,Lazy Loading,我最近正在使用Hibernate,需要显示以注释作为外键(@OneToMany)的主题,如下所示: 主题类 ... @OneToMany(fetch = FetchType.LAZY, mappedBy = "topic") public Set<Comment> getComments() { return this.communityComments; } ... 当我使用findByExample获取主题时,将返回一组主题。问题是如何迭代集合?当我执行以下代码时:
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "topic")
public Set<Comment> getComments() {
return this.communityComments;
}
...
当我使用findByExample
获取主题时,将返回一组主题。问题是如何迭代集合?当我执行以下代码时:
Set<Topic> oriList = topicDAO.findByExample(OneExample);
Iterator<Topic> it = oriList.iterator();
Set oriList=topicDAO.findByExample(一个示例);
迭代器it=oriList.Iterator();
它显示“无会话”异常。原因是我认为oriList.iterator()
试图访问惰性对象-注释
有没有什么方法可以用最小的改变来解决这个问题
或者有没有办法不使用迭代器将所有注释设置为
null
这里您的问题是获取会话
您应该尝试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;
}
}
最小的改变是让他们不懒惰…
FetchType.EAGER
关于这个特定问题有一个很好的博客,你可以在这里看看,它讨论了简单和最佳的解决方案。你还可以在条件查询setFetchMode(“communityComments”,FetchMode.EAGER)中设置fetch模式EAGER for comments集合。这将覆盖条件查询中的延迟提取。@Steven发布stacktrace。我认为这与评论无关。
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;
}
}