JPA EntiityManager.find方法
阿新 • • 發佈:2020-07-29
find 方法
- 立即載入:在呼叫find方法的時候,就會發送sql語句查詢資料庫。
- 找到返回實體類物件,可以用於remove,setter,remove之後還可以呼叫persist儲存。
- 找不到返回null。
find 方法測試
find之後setter實現更新
@Test public void test1() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Student s = em.find(Student.class, 1L); /* 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=? */ s.setSage(999); // ORM思想:操作Managed狀態的實體類物件就相當於操作表中的記錄 tx.commit(); /* Hibernate: update Student set sage=?, sname=? where sid=? */ em.close(); factory.close(); }
find之後remove實現刪除
@Test public void test2() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Student s = em.find(Student.class, 1L); /* 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=? */ em.remove(s); // ORM思想:操作Managed狀態的實體類物件就相當於操作表中的記錄 tx.commit(); /* Hibernate: delete from Student where sid=? */ em.close(); factory.close(); }
find之後remove再persist相當於刪除後又儲存
@Test public void test() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Student s = em.find(Student.class, 1L); /* 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=? */ em.remove(s); em.persist(s); tx.commit(); em.close(); factory.close(); }
find找不到返回null
@Test
public void test2() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa");
EntityManager em = factory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Student s = em.find(Student.class, 1027500L); // 找不到返回 null
/*
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=?
*/
System.out.println(s); // null
tx.commit();
em.close();
factory.close();
}