简体   繁体   中英

JPA EntityTransaction, creating and persisting a new object

I have some confusion with some simple examples i am looking at for Eclipselink and persisting objects. Very new to this. Does it matter at what point you create and mutate an object to save in a database? eg Does all of the work you do with the object have to be done AFTER em.getTransaction().begin(); is called? or can you do what ever you need with that object and then begin, persist, close?

I am using this example with Tomcat. non-jta RESOURCE_LOCAL

The differences in question below:

    EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();

 // Creating and mutating object BEFORE begin() is called
    Todo todo = new Todo();
    todo.setSummary("sum");
    todo.setDescription("desc");

    // create new todo
    em.getTransaction().begin();
    em.persist(todo);
    em.getTransaction().commit();

Vs

EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();


em.getTransaction().begin();

// Creating and mutating object AFTER begin() is called
Todo todo = new Todo();
todo.setSummary("sum");
todo.setDescription("desc");

em.persist(todo);
em.getTransaction().commit();

There is no difference, when you create you object. after begin or before begin.

In fact there is no difference. Because transaction deals only with saving in the database of the persisted entity (entity is a java object: todo in your case). The last thing you do with you entity is flushing it in database (with commit() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM