Search code examples
javahibernatejpatransactions

JPA Hibernate transaction issue


I accidentally discoverd that I can persist changes on a object, even if I dont write them inside the transaction. I wounder how this happend, cuz in theory, I should'nt be able to change the age value in the database, if I dont write the changes inside the transaction. PS: If I remove the last 2 lines, it does nothing to the db, as expected.

var emf = Persistence.createEntityManagerFactory("java2c2PU");
var em = emf.createEntityManager();
var p = em.find(Pisica.class, 5);

p.setAge(5);

em.getTransaction().begin();
    
em.getTransaction().commit();

Solution

  • You are in the EXTENDED JPA mode. So the Entity Manager is not bound to the transaction.

    Changes are preserved in the Persistence Context. And as soon you commit a transaction the changes are flushed and committed.