我最近使用Hibernate,需要如下,以顯示它有意見作爲其外交重點(@OneToMany)主題:Hibernate的名單沒有遲緩對象
Topic.class
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "topic")
public Set<Comment> getComments() {
return this.communityComments;
}
...
我使用Hibernate工具到發電機密封其中包含的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();
它顯示'沒有會話'異常。原因是我認爲oriList.iterator()
試圖訪問懶惰的對象 - 評論。
有什麼辦法可以用最小的改變來解決這個問題嗎?
或者是否有任何方法可以在不使用迭代器的情況下將所有註釋設置爲null
?
最小的變化將是使他們不懶...'FetchType.EAGER' – Coderchu
有關於這個問題一個很好的博客,你可以看看這裏的http://javarevisited.blogspot。 in/2014/04/orghibernatelazyinitializationException-Could-not-initialize-proxy-no-session-hibernate-java.html 它討論了簡單和最優解決方案 – Vihar
您還可以在標準查詢中設置渴望評論集合的獲取模式setFetchMode(「communityComments」,FetchMode.EAGER)。這將覆蓋條件查詢中的惰性提取。 – akki