簡體   English   中英

Hibernate Load不會從會話緩存中獲取對象

[英]Hibernate Load does not fetch object from session cache

我嘗試下面的代碼:

Student s1 = (Student) s.load(Student.class, 5); // this records not there in DB
 try {
    s1.setName("Kaushik1");
} catch (ObjectNotFoundException e) {
    s1 = new Student();
    s1.setId(5);
    s1.setName("trying1");
}
s.saveOrUpdate(s1);

Student s2 = (Student) s.load(Student.class, 5);
try {
    s2.setName("Kaushik2");
} catch (ObjectNotFoundException e) {
    //Why should it throw ObjectNotFoundException now
    s2 = new Student();
    s2.setId(5);
    s2.setName("trying2");
}
s.saveOrUpdate(s2); //Why it throws NonUniqueObjectException

我使用load從ID為5的數據庫中獲取記錄。 記錄不存在。 然后我嘗試在對象上調用setter,這引發了異常。 同意!

由於該記錄不存在,因此我創建了一個新對象並稱為saveOrUpdate() 所以現在我假設ID#5的對象在會話緩存中。

現在,我再次嘗試為ID#5調用load()方法並調用其setter。 它將再次引發ObjectNotFoundException。

問題1

為什么它不能從會話緩存中選擇記錄?

當我創建新對象並嘗試調用saveOrUpdate()它給出了NonUniqueObjectException

org.hibernate.NonUniqueObjectException:具有相同標識符值的另一個對象已與該會話關聯:[com.cts.closr.Student#5]

它引發了ObjectNotFoundException,現在說“對象已經與會話關聯”。 這不是矛盾的嗎?

問題2

這是否意味着load()方法從不檢查會話上下文? 它總是從數據庫獲取嗎? 那么在這種情況下,我必須使用get()方法嗎?

該文件說:

如果Session引發異常(包括任何SQLException),請立即回滾數據庫事務,調用Session.close()並丟棄Session實例。 某些會話方法不會使會話保持一致狀態。 Hibernate拋出的異常不能被視為可恢復的。

因此,使用Session.load() ,捕獲異常並繼續使用會話是一個很大的禁忌。 當您認為對象必須存在於數據庫中時,必須使用Session.load() ,否則,將引發異常。 如果不確定對象是否存在,請使用Session.get() ,測試返回的對象是否為null,並采取相應的措施。

“現在,我再次嘗試為ID#5調用load()方法”,我相信您鍵入的錯誤。

    Student s2 = (Student)s.load(Student.class, 6); 

應該是

    Student s2 = (Student)s.load(Student.class, 5);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM