JPA加載,更新,刪除


juint中:

static EntityManager em=null;
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("jpaPU");
        em=emf.createEntityManager();
    }

1.兩種方法:

Person person=em.find(Person.class, 1);
已經經過泛型處理。find方法相當於Hibernate里面的get方法。如果沒有找到相應數據,就返回null.

Person person=em.getReference(Person.class,2);
如果這條記錄不存在,單單這句話執行不會出錯(返回代理)。但當使用person.getName()時會報實體不存在的異常。   相當於Hibernate里面的load方法。而且這種方法是延遲加載的。只有當實際訪問實體屬性時才到數據庫中去執行查詢。

Person person=em.getReference(Person.class,1);
    em.close();
    System.out.println(person.getName());
   

此句話會報錯,因為person的屬性其實沒有加載出來。

Person person=em.find(Person.class, 1);

em.close();
System.out.println(person.getName());

而這段可以正確執行,因為person在find的時候就已經獲取了相應的屬性。

2.更新:

先看JPA里面的實體的狀態:

新建、托管、游離、刪除

處於托管狀態下的實體發生的任何改變當實體管理器關閉的時候都會自動更新到數據庫。

注意要更新必須要開啟事務

em.getTransaction().begin();

Person person=em.find(Person.class, 1);
em.close();
person.setName("tazi00");

以上是不能成功更新的。以下可以修改。

em.getTransaction().begin();
        Person person=em.find(Person.class, 1);
        person.setName("tazi00");
       em.getTransaction().commit();
        em.close();

 

em.getTransaction().begin();
        Person person=em.find(Person.class, 1);
        em.clear(); //把實體管理器中的所有的實體都變成游離狀態
        person.setName("tazi22");
        em.merge(person);
        em.getTransaction().commit();
        em.close();

em.getTransaction().begin();
        Person person=em.find(Person.class, 1);
        em.remove(person); //操作的也必須是持久化狀態,或者托管狀態的對象
        em.getTransaction().commit();
        em.close();

以下代碼會報錯

em.getTransaction().begin();
        Person person=new Person();
        person.setId(1);
        em.remove(person);
        em.getTransaction().commit();
        em.close();

java.lang.IllegalArgumentException: Removing a detached instance com.tazi.domin.Person#1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM