Unique constraint with JPA and Bean Validation

Viewed 47558

I'd like to have a @Unique constraint with Bean Validation, but that is not provided by the standard. If I would use JPA's @UniqueConstraint I wouldn't have a unique validation and error reporting mechanism.

Is there a way to define @Unique as a Bean Validation constraint and combine it with JPA, such that JPA creates a column with an unique constraint and checks wheter a value is unique or not?

5 Answers

You should try (insert or update), catch the exception and do some action. For example in a JSF backing bean :

try {
   dao.create(record);//or dao.modify(record)
   //add message success
} catch(EJBException e) {
   //look for origin of error (duplicate label, duplicate code, ...)
   var err = dao.isUnique(record);
   if(err == null) throw e;//other error
   String clientId = null;
   String message = null;
   switch(err) {
      case CODE:
        clientId = "client_id_of_input_code";
        message = "duplicate code";
        break;
      case LABEL:
        clientId = "client_id_of_input_label";
        message = "duplicate label";
        break;
      default:
        throw new AssertionError();//or something else
   }
   facesContext.addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_ERROR, message));
   facesContext.validationFailed();
}

Another option is to check before the insertion/modification. This can be time consuming and doesn't prevent the error to happen in the end.

Related