My intention is to return a newly persisted entity just in the same business call to a client in order to get the generated primary key needed for further business logic. Calling a finder method to find the entity by name or some known attributes again would cause a second server roundtrip I would like to avoid (time is money ;-). So I created the following method:
public Entity persist(Entity entity) {
em.persist(entity);
em.flush();
em.refresh(entity);
// now the entity has an id
return entity;
}
But now I’m wondering whether this is the right way to do this. It feels “strange” somehow. The JPA specification is quite clear about this: the EntityManager’s persist() method returns void – sounds like “fire and forget” for me. But my client is dependent on the primary key. Is there an alternative solution to my method above? Is this best practice in my case? What do you think?
There is no single “right way” … otherwise that would be the API. You call the methods appropriate for your application, and the use-case of that method. If you need the object in the datastore immediately after, then you call flush(), otherwise you don’t. If you have other processes that can update things then you call refresh() otherwise you don’t. And so on.