问题描述
这个问题一遍又一遍地被询问/提及,但是我找不到我做错了什么还是该问题是真实的":我有一个简单的Oracle表的实体类,其中有一个字段应该是唯一的.它在数据库中具有唯一的约束.在实体定义中,我添加了JPA批注-
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;
...
我正在使用JBoss问题是,我总是会陷入休眠异常,如果我想知道约束违规,它将把我与JPA实现联系起来.有没有办法在这种情况下捕获持久性过期并提供用户友好的消息?如果不是,则@Column(name = "uni_field", unique = true)
或uniqueConstraints = @UniqueConstraint(columnNames = "uni_field")
有什么用?
I am using JBossThe 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")
?
推荐答案
如果要显示注释中定义的必填字段"消息,则可以捕获如下异常:
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();
}
}
作为参考,请检查 OpenJPA Bean验证入门
这篇关于JPA批注和ConstraintViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!