JPA的entityManager的find方法与getReference方法的区别
場景
JPA入門簡介與搭建HelloWorld(附代碼下載):
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103473937
注:
博客主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現(xiàn)
find
返回指定的 OID 對應的實體類對象,如果這個實體存在于當前的持久化環(huán)境,則返回一個被緩存的對象;否則會創(chuàng)建一個新的 Entity, 并加載數(shù)據(jù)庫中相關信息;若 OID 不存在于數(shù)據(jù)庫中,則返回一個 null。第一個參數(shù)為被查詢的實體類類型,第二個參數(shù)為待查找實體的主鍵值。
getReference
與find()方法類似,不同的是:如果緩存中不存在指定的 Entity, EntityManager 會創(chuàng)建一個 Entity 類的代理,但是不會立即加載數(shù)據(jù)庫中的信息,只有第一次真正使用此 Entity 的屬性才加載,所以如果此 OID 在數(shù)據(jù)庫不存在,getReference() 不會返回 null 值, 而是拋出EntityNotFoundException
單元測試
測試find方法
@Test public void testFind() {Customer customer = entityManager.find(Customer.class, 3);System.out.println("-------------------------------------");System.out.println(customer); }測試結果
?
測試getReference方法
@Test public void testGetReference(){Customer customer = entityManager.getReference(Customer.class, 3);System.out.println(customer.getClass().getName());??System.out.println("-------------------------------------");??System.out.println(customer); }?
通過上面的測試可知
find方法類似于hibernate中Session的get方法。
getReference方法類似于hibernate的Session的load方法。
find()做了一次select的操作,而getReference并沒有做有關數(shù)據(jù)庫的操作,而是返回一個代理,這樣它就減少了連接數(shù)據(jù)庫和從數(shù)據(jù)庫加載持久狀態(tài)的開銷。
?
總結
以上是生活随笔為你收集整理的JPA的entityManager的find方法与getReference方法的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse中Junit测试中@Bef
- 下一篇: JPA的entityManager的fi