0

I try to persist an object in postgres database. After the persist call, I return my object, I modify my object, research the object (with function find of my entity manager) and data is still the same (before my object's modification).

I believe after persist, the object is link to database, and a modification with a setter is automatically persist in database

I use JPA2.1 with hibernate, wildfly 13. I already check theses answer :

What is the difference between persist() and merge() in JPA and Hibernate?

JPA EntityManager: Why use persist() over merge()?

I have a repository class with an entity manager :

@Transactional(TxType.SUPPORTS)
class testRepository{
   @PersistenceContext(unitName = "xxxPU")
   private EntityManager em;
   [...]

   @Transactional(TxType.REQUIRED)
   public Test create(@NotNull Test test) {
       em.persist(test);
       return test;
   }

   public Test find(@NotNull Long id) {
       return this.em.find(Test.class, id);
   }
   [...]
  }

And my test class with the folowing test :

    Test test = new Test(null, null, "12", "RUE DE LA PAIX", "75000", "PARIS", null);
    test= testRepository.create(test);

I believe at this point object test is link to database, but if i call this code :

  test.setAValue("93000");

And I search this object :

  Test testFind = testRepository.find(test.getId());

And compare the two object, I have a test error, because test.aValue = 75000 and testFind.aValue=93000.

After setter, if I made a call to a merge function, testFind.aValue has the correct value.

I don't understand why my object is not link to my database after the persist call.

GGENIER
  • 1
  • 3
  • Your entity will be updated once the unit of work is completed. If you are doing the update and the fetching in the same method if will not write to the database until the method is completed. Check https://stackoverflow.com/a/8190986/1771729 – Aitor Jan 24 '19 at 23:02
  • Thank you. In fact, I think Hibernate make a begin/commit for function create. And after commit object is detached. If I made my own transaction management with a begin/commit in my test function, everything works. – GGENIER Feb 01 '19 at 11:38

0 Answers0