JPA基礎(七):使用JPA載入_更新_刪除對象

來源:互聯網
上載者:User

我們目前使用的是Hibernate,實際上我們操縱EntityManager對象時,它內部是操縱了Hibernate裡面的session對象,只是對session對象做了封裝而已。

1     @Test
2 public void getPerson(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 Person p=em.find(Person.class, 1);//相當於Hibernate的get方法
6 System.out.println(p.getName());
7 em.close();
8 factory.close();
9 }

如果不存在id為1的Person時,返回null。

 

1     @Test
2 public void getPerson2(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 Person p=em.getReference(Person.class, 1);//相當於Hibernate的load方法,消極式載入
6 System.out.println(p.getName());
7 em.close();
8 factory.close();
9 }

 

 1     @Test
2 public void update(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 em.getTransaction().begin();
6 Person p=em.find(Person.class, 1);
7 p.setName("jame");//p處於持久態,所以直接更改,在事務提交時會與資料庫進行同步
8 em.getTransaction().commit();
9 em.close();
10 factory.close();
11 }

 

 1     @Test
2 public void update2(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 em.getTransaction().begin();
6 Person p=em.find(Person.class, 1);
7 em.clear();////把實體管理器中的所有實體變成游離狀態。
8 p.setName("jim");
9 em.merge(p);
10 em.getTransaction().commit();
11 em.close();
12 factory.close();
13 }

在clear之後,p變成了游離狀態,這時候對游離狀態的實體進行更新的話(p.setName("jim");),更新的資料是不能同步到資料庫的。可以採用方法em.merge(p);這方法是用於把在游離狀態時候的更新同步到資料庫。

 1     @Test
2 public void delete(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 em.getTransaction().begin();
6 Person p=em.find(Person.class, 2);
7 em.remove(p);//刪除的bean對象也必須是處於託管狀態的對象才能被刪除成功。
8 em.getTransaction().commit();
9 em.close();
10 factory.close();
11 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.