What does EntityManager.flush do and why do I need to use it?

spartikus picture spartikus · Jul 17, 2013 · Viewed 121.7k times · Source

I have an EJB where I am saving an object to the database. In an example I have seen, once this data is saved (EntityManager.persist) there is a call to EntityManager.flush(); Why do I need to do this? The object I am saving is not attached and not used later in the method. In fact, once saved the method returns and I would expect the resources to be released. (The example code does this on a remove call as well.)

if (somecondition) {
    entityManager.persist(unAttachedEntity);
} else {
    attachedEntityObject.setId(unAttachedEntity.getId());
}
entityManager.flush();

Answer

Benoit Wickramarachi picture Benoit Wickramarachi · Jul 17, 2013

A call to EntityManager.flush(); will force the data to be persist in the database immediately as EntityManager.persist() will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).