Catching constraint violations in JPA 2.0.

Posted by Dennetik on Stack Overflow See other posts from Stack Overflow or by Dennetik
Published on 2010-05-23T17:59:15Z Indexed on 2010/05/23 21:01 UTC
Read the original article Hit count: 260

Consider the following entity class, used with, for example, EclipseLink 2.0.2 - where the link attribute is not the primary key, but unique nontheless.

@Entity
public class Profile {  
  @Id 
  private Long id;

  @Column(unique = true)
  private String link;

  // Some more attributes and getter and setter methods
}

When I insert records with a duplicate value for the link attribute, EclipseLink does not throw a EntityExistsException, but throws a DatabaseException, with the message explaining that the unique constraint was violated.

This doesn't seem very usefull, as there would not be a simple, database independent, way to catch this exception. What would be the advised way to deal with this?

A few things that I have considered are:

  • Checking the error code on the DatabaseException - I fear that this error code, though, is the native error code for the database;
  • Checking the existence of a Profile with the specific value for link beforehand - this obviously would result in an enormous amount of superfluous queries.

© Stack Overflow or respective owner

Related posts about java

Related posts about jpa