Question

I'm trying to understand how the synchronisation between persistence context and the database works.The code below runs pretty good :

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

em.getTransaction().begin();

for(String name : names) {
    Student toInsert = new Student();
    toInsert.setName(name);
    em.persist(toInsert);
}

em.getTransaction().commit();
  • But where the flush() method goes ? Do I even have to use it ?

  • Do I have to getTransaction.begin() everytime ?

  • What is the standard form to update information in the database with Hibernate ?

Was it helpful?

Solution

  1. Flush is not required as commit will flush it automatically for you. You need to flush when performing a long running transaction where the data needs to be saved to the DB to avoid memory heap (or) if you need to sync the data in the session to the DB for some reason.
  2. If you feel that starting transactions is tedious, you ma use spring declarative transactions. By doing so, the spring will take care of creating transaction boundaries around a method and also commits/rolls back the data depending on what happens in the method. Easy to use, but has its own limitations like it does not allow us to handle the rollback.
  3. Updating object depends on the context of the object(has one object in the session/no object in the session) use session.merge(object) mostly as it solves a couple of scenarios for you. But make sure, you have all the data set on the detached object that needs to be saved, or else you end up deleting the data which was not loaded.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top