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();
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).