Link to home
Start Free TrialLog in
Avatar of HappyEngineer
HappyEngineer

asked on

What is the proper way to use JPA to attempt persist and then merge if it exists? (INSERT or UPDATE)

There is a pattern when attempting to store things in the DB. In some situations there may be multiple threads attempting to create the same object, so the best way to deal with this is to attempt to insert the object and then, if an exception is thrown, update the object instead.

But, I don't know how to do that properly in JPA. If I try to persist an object inside of a transaction, the failure exception won't be thrown until the transaction attempts a commit. So I have to do the persist inside of a transaction by itself. But, if I do that, hibernate logs a huge long stack trace for org.hibernate.exception.ConstraintViolationException even though I am already catching and handling it.

Ultimately what I do does work. But every single failed insert results in a huge stack trace. I don't want to use log4j to block those stack traces because I sometimes those messages could be for actual errors.

What should I do to properly implement the INSERT or UPDATE pattern using JPA?
Avatar of Mr_It
Mr_It

I believe you can also call merge on new entity instances. A new record will be created if necessary on flush or transaction commit.

In the specs you can read (3.2.4.1):
The semantics of the merge operation applied to an entity X are as follows:
...
If X is a new entity instance, a new managed entity instance X' is created and the state of X is
copied into the new managed entity instance X'.
...

So you might wonder why they also added the persist method? I can think of use cases where you want to be sure that a new record is created (instead of updated). Or a certain user migth only be permitted to create new records, not to update them. Also note that the persist operation is the most performant of both (the instance is not copied).
ASKER CERTIFIED SOLUTION
Avatar of HappyEngineer
HappyEngineer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial