JPA annotation and ConstraintViolationException

泪湿孤枕 提交于 2019-12-25 04:09:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!