2014-01-31 57 views
-1

如果我們將一個屬性註釋爲惰性初始化爲true,那麼我們無法訪問該屬性。例如Hibernate惰性初始化要求

@ManyToOne(fetch=FetchType.LAZY) 
    @JoinColumn(name="orgTypeID") 
    private OrganizationType type; 

我們無法訪問組織類型。那麼在課堂上宣佈這樣的領域和吸氣劑和製劑師有什麼需要?

我們不需要加入。感謝您是否可以解釋這一點。

+0

爲什麼你不能使用getter訪問它?你是否得到某種錯誤?你是什​​麼意思_我們不需要加入_?你只需要映射'OrganizationType' ID? –

+0

如果我們嘗試訪問它,該對象爲空。但實際上數據在那裏。 – user2622132

+0

當我調試組織類型值爲'org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer' – user2622132

回答

0

具有「懶惰」提取的對象不會被提取,除非被要求提供。

爲了緩慢發生抓取,對象必須仍然處於會話上下文中。如果嘗試在會話上下文(分離對象)之外訪問此懶惰屬性,則會在服務器上看到一個懶惰的初始化錯誤 - 無會話問題。

要將對象放回會話中,您必須打開一個會話並將該對象合併到會話中並嘗試獲取該懶惰屬性。

要解決您的問題,如果您預計將來會提取此懶惰屬性,則必須在以下列方式加載父對象時手動獲取它。

Session session = factory.getSession(); 

Class clas = session.find(Class.class, id); 

clas.type();//here you are anticipating that it will be used somewhere else, so force it to load 

session.close(); 
// clas.type(); // Hypothetically, if you try to load the type here, this may not work as the session is closed before this line. the object is now in detached state. 

希望它回答你的問題。

相關問題