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 practic开发者_JAVA百科e 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.
The entity passed to persist
is made persistent. That means that, now or later in the transaction, it will be written to database and an ID will be generated for this entity. The instance itself (the one you passed to persist
) will have the generated ID assigned to it. So, just persisting the entity is, most of the time, sufficient, since when the client will call getId()
, the transaction where persist
has been called has been committed already, which means that the entity has an ID.
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 need the id within the same transaction, then yes, you will need to flush
or otherwise commit the transaction, and you will probably need to refresh
the entity as well.
精彩评论