我有一個帶有主鍵 ID 的學生表。我正在使用 Hibernate 和會話的加載命令來獲取記錄。我正在獲取 id 1 和 2 的記錄都不存在于資料庫中。我知道 get() 在這種情況下會回傳 null,而 load() 在這種情況下會回傳 ObjectNotFoundException()。但我得到一個奇怪的輸出。
Student student1 = session.get(Student.class, 1);
System.out.println(student1);
Student student2 = session.load(Student.class, 2);
System.out.println("ABC");
System.out.println(student2);
我得到的輸出 -
null
ABC
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.tutorial.Student#2]
我期待的輸出 -
null
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.tutorial.Student#2]
有什么我沒有得到的嗎?
uj5u.com熱心網友回復:
如果您使用session.load()加載物體并且session.get()之前未在同一事務中檢索到該物體,它將回傳一個未初始化的代理,這是它的預期行為。
由于回傳的代理未初始化,因此在此期間沒有資料庫訪問權限,因此即使 ID 無效,session.load()它也不會在此期間拋出。ObjectNotFoundException
如果您在(1)之后訪問物體的屬性而不是其 ID,它只會從資料庫中選擇記錄來實際初始化代理。在初始化代理程序中,如果發現該 ID 不存在 DB 記錄,它將拋出ObjectNotFoundException。現在,當您列印它時,您正在student2通過它訪問它的屬性,因此當時被拋出。toString()ObjectNotFoundException
另請參閱我大約 10 年前關于此處session.get()和此處session.load()之間差異的答案。
注(1):行為實際上是由配置定義的,具體hibernate.jpa.compliance.proxy請看
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414185.html
標籤:
上一篇:SpringBootJPA-User和UserStats之間映射的多對一關系,但是當我從Repo獲取用戶時,沒有UserStats物體?
