Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle JPA unique constraint violations?

When a unique constraint is violated, a javax.persistence.RollbackException is thrown. But there could be multiple reasons to throw a RollbackException. How can I find out that a unique constraint was violated?

try {     repository.save(article); } catch(javax.persistence.RollbackException e) {     // how to find out the reason for the rollback exception? } 
like image 853
deamon Avatar asked Aug 17 '10 12:08

deamon


People also ask

How do you handle unique constraint violations?

To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result. Use the UnitOfWork in the controller to explicitly commit pending changes and see if there are any uniqueness constraint violations.

What is unique constraint violation?

A unique constraint violation occurs when an UPDATE or INSERT statement attempts to insert a record with a key that already exists in the table. Take a look at the package that is throwing the error.

How do you handle unique constraint exceptions in PL SQL?

begin merge into some_table st using (select 'some' name, 'values' value from dual) v on (st.name=v.name) when matched then update set st. value=v. value when not matched then insert (name, value) values (v.name, v.

How do I make two columns unique in JPA?

A unique constraint can be either a column constraint or a table constraint. At the table level, we can define unique constraints across multiple columns. JPA allows us to define unique constraints in our code using @Column(unique=true) and @UniqueConstraint.


1 Answers

How can I find out that a unique constraint was violated?

Exception are chained, you have to call getCause() recursively to get the provider specific exception (and maybe go down to the SQLException) to translate it into something your application can handle nicely for your user. The following will print the chain of exception:

for (t = e.getCause(); t != null; t = t.getCause()) {     logger.debug("Exception:" + t); } 

For the exception handling and the "translation", you could do something like what Spring does (see the various JpaDialect classes, e.g. HibernateJpaDialect to get an idea).

All this is not nice, this code won't be portable and finding what attribute(s) caused the violation won't be easy. This somehow confirms that there is no elegant and portable way to handle constraint violations in JPA.

like image 160
Pascal Thivent Avatar answered Sep 30 '22 07:09

Pascal Thivent