我有一个数据库表,它同时具有外键和唯一键约束。为了在数据库表中进行更改,我正在使用使用 hibernate 的 java 应用程序。更准确地说,我正在执行 Session.save() 来更改数据库表。我的代码如下所示。
try{
transaction.begin();
------logic-------
session.save();
transaction.commit();
}catch(ConstarintViolationException exception){
---here is problem------
}
如果发生任何类型约束冲突,hibernate 会抛出名为 ConstraintViolationException
的相同异常。
我的问题是我应该做什么来确定是什么约束导致了异常。我尝试做
exception.getConstraintName()
但不幸的是我得到 null
作为输出。
我想区分这两种情况,因为我想在将其发送给客户端之前将 hibernate 异常转换为我自己的异常。
最佳答案
我想说让数据库检测违反约束的情况......
或者
您可以拥有类似下面的类的内容,这可能有助于您捕获违反约束的异常...
public class DataIntegrityViolationExceptionsAdvice {
public void afterThrowing(DataIntegrityViolationException ex) throws DataIntegrityViolationException {
// extract the affected database constraint name:
String constraintName = null;
if ((ex.getCause() != null) && (ex.getCause() instanceof ConstraintViolationException)) {
constraintName = ((ConstraintViolationException) ex.getCause()).getConstraintName();
}
// create a detailed message from the constraint name if possible
String message = ConstraintMsgKeyMappingResolver.map(constraintName);
if (message != null) {
throw new DetailedConstraintViolationException(message, ex);
}
throw ex;
}
}
关于java - 区分 hibernate 中不同的约束违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22586576/