We help IT Professionals succeed at work.
Get Started

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

HappyEngineer
on
4,133 Views
Last Modified: 2012-05-05
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?
Comment
Watch Question
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE