JPA EntiityManager.getReference方法
阿新 • • 發佈:2020-08-01
getReference 方法
- 延遲載入:什麼時候用什麼時候查詢
- 找到返回 代理物件
- 找不到 丟擲 javax.persistence.EntityNotFoundException
getReference 方法測試
@Test public void test() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Student s1 = em.getReference(Student.class, 1L); System.out.println("---"); System.out.println(s1); /* --- Hibernate: select student0_.sid as sid1_0_0_, student0_.sage as sage2_0_0_, student0_.sname as sname3_0_0_ from Student student0_ where student0_.sid=? Student{sid=1, sname='劉備', sage=100} */ Student s2 = em.getReference(Student.class, 9999L); System.out.println("---"); try { System.out.println(s2); } catch (EntityNotFoundException e) { System.out.println("沒查到"); } /* --- Hibernate: select student0_.sid as sid1_0_0_, student0_.sage as sage2_0_0_, student0_.sname as sname3_0_0_ from Student student0_ where student0_.sid=? 沒查到 */ tx.commit(); em.close(); factory.close(); }