green marker
green marker

Reputation: 1639

Entity is not persisted using EclipseLink

I'm learning JPA. In the code below I'm trying to persist Point, then list Points to check and it turns out that it haven't been saved. Why?

Thank you!

    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);
    }

Whole project: https://github.com/greenmarker/EclipseLinkTest

Upvotes: 2

Views: 475

Answers (1)

Neil Stockton
Neil Stockton

Reputation: 11531

Since you have no transaction there, then nothing is committed.

Some JPA providers will allow "non-transactional" writes (what you're trying to do there, e.g DataNucleus JPA), but many won't, so you need to do

em.getTransaction().begin();

... (persist, merge, remove calls)

em.getTransaction().commit();

if you want vendor-independent persistence code

Upvotes: 2

Related Questions