Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling persist() flush() and refresh() in one method to persist an entity the right way?

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?

like image 847
mwalter Avatar asked Aug 26 '11 15:08

mwalter


1 Answers

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.

like image 117
gatti Avatar answered Nov 15 '22 23:11

gatti