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?
If using eclipselink, you should try the
@ReturnInsert
annotation. You set it with the @Id and you are telling Eclipselink to get the ID from the DB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With