Java 捕获JPA2.0中的约束冲突
考虑以下实体类,例如与EclipseLink 2.0.2一起使用,其中Java 捕获JPA2.0中的约束冲突,java,jpa,try-catch,eclipselink,unique-constraint,Java,Jpa,Try Catch,Eclipselink,Unique Constraint,考虑以下实体类,例如与EclipseLink 2.0.2一起使用,其中link属性不是主键,而是唯一的非主键 @Entity public class Profile { @Id private Long id; @Column(unique = true) private String link; // Some more attributes and getter and setter methods } 当我为链接属性插入具有重复值的记录时,EclipseL
link
属性不是主键,而是唯一的非主键
@Entity
public class Profile {
@Id
private Long id;
@Column(unique = true)
private String link;
// Some more attributes and getter and setter methods
}
当我为链接
属性插入具有重复值的记录时,EclipseLink不会抛出EntityExistsException
,而是抛出数据库异常
,并显示一条消息,说明违反了唯一约束
这似乎不是很有用,因为没有一种简单的、独立于数据库的方法来捕获此异常。处理这个问题的建议方法是什么
我考虑过的几件事是:
- 检查
——但我担心此错误代码是数据库的本机错误代码李>数据库异常上的错误代码
- 事先用
链接的特定值检查
——这显然会导致大量多余的查询配置文件的存在性
与上面的答案相同,请参见我的。很遗憾,他们在JPA中没有ConstraintViolationException。我创建了一个helper方法来确定PersistenceException是否是给定类的约束冲突——不过它只是hibernate。我想有一种方法可以使用其他实现来实现
protected Boolean isUniqueConstraintViolation(PersistenceException ex, Class entity) {
if (((NonUniqueObjectException)ex.getCause()).getEntityName().equals(entity.getName())) {
return true;
}
return false;
}
既然你在这里特别提到了EclipseLink:你知道其他JPA提供商的行为是否正确吗?@Hank也许这个问题在最近的版本中已经解决了,我不能说。但据我所知,在这种情况下,Hibernate确实抛出了一个
持久异常。请投赞成票,以便我们能够修复此问题: