When creating new entities from user input I can’t be sure that there is no other entity with identical data. The only examples I was able to find used predefined Ids, so one could check if the entity exists by calling entityManager.find(id). If the id is generated, I see several ways to persist safely:
- call
entityManager.persistand hope for the best – catching theEntityExistsExceptionand either swallowing it or displaying an error message - call
entityManager.mergeand let JPA do the checking…will it always work properly? - search for the entity by a query – jPQL or criteria and call
entityManager.persistif not found
My intuition is to go with the third approach, but is there a better way still?
I am working with JPA 2 and would like to avoid vendor-specific solutions (like Hibernate’sSessionManager.saveOrUpdate)
If you really can’t predict whether the newly generated ID will be unique I’d definitely go with the third approach.
Also, I don’t think you’ll need Criteria for such a simple query, and in most cases the cost of that extra query won’t be very costly.