问题
This question is being asked/mentioned over and over but I could not find if I am doing something wrong or that the problem is "real": I have an entity class for a simple Oracle table in which there is one field that should be unique. It has a unique constraint in the DB. In the entity definition I added the JPA annotation -
@Entity
@Table(name = "tbl", uniqueConstraints = @UniqueConstraint(columnNames = "uni_field"))
public class MyTable implements Serializable {
...
@Column(name = "uni_field", unique = true)
@NotNull(message = "Field is required.")
private String field;
...
I am using JBoss
The problem is that I am always ending up in hibernate exception which tie me up to the JPA implementation if I want to know the constraint violation.
Is there a way to catch a persistency expcetion in such case and provide a user friendly message?
If not than what use is there in the @Column(name = "uni_field", unique = true)
or uniqueConstraints = @UniqueConstraint(columnNames = "uni_field")
?
回答1:
If you want to show "Field is required" message as defined in your annotation, you could catch your exception like this:
catch(javax.validation.ConstraintViolationException cve){
Set<ConstraintViolation<?>> cvs = cve.getConstraintViolations();
String errMsg = "";
for (ConstraintViolation<?> cv : cvs) {
errMsg = cv.getMessage();
}
}
For reference, please check OpenJPA Bean Validation Primer
来源:https://stackoverflow.com/questions/16385991/jpa-annotation-and-constraintviolationexception