2015-12-22 68 views
2

我在學習JPA。在下面的代碼中,我試圖堅持Point,然後列出Points進行檢查,結果證明它尚未保存。爲什麼?實體未使用EclipseLink持久保存

謝謝!

PersistenceProvider provider = new PersistenceProvider(); 
    EntityManagerFactory emf = provider.createEntityManagerFactory("sample", null); 

    EntityManager em = emf.createEntityManager(); 
    // DROP TABLE POINT 
    // CREATE TABLE POINT (ID BIGINT NOT NULL, X DOUBLE, Y DOUBLE, PRIMARY KEY (ID)) 
    // DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN' 
    // SELECT * FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN' 
    // INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0) 


    Point p = new Point(1, 1); 
    em.persist(p); 
    // UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ? 
    // bind => [2 parameters bound] 
    // SELECT SEQ_COUNT FROM SEQUENCE WHERE SEQ_NAME = ? 
    // bind => [1 parameter bound] 
    em.close(); 


    EntityManager em2 = emf.createEntityManager(); 
    Query query = em2.createQuery("select p from Point p"); 
    List list = query.getResultList(); 
    // SELECT ID, X, Y FROM POINT 
    System.out.println("Found objects: " + list.size()); 
    // Found objects: 0 
    for (Object elt: list){ 
     System.out.println(elt); 
    } 

整個工程:https://github.com/greenmarker/EclipseLinkTest

回答

2

既然你沒有交易在那裏,再沒有什麼承諾。

一些JPA提供商將允許「非事務寫道:」(你想在那裏做,如DataNucleus將JPA是什麼),但很多不會,所以你需要,如果你做

em.getTransaction().begin(); 

... (persist, merge, remove calls) 

em.getTransaction().commit(); 

希望獨立於供應商的持久性代碼

相關問題