hibernate SQLIntegrityConstraintViolationException

时间:2013-05-23 13:29:18

标签: java oracle hibernate

我有一个oracle表,在几个字段上有一个独特的约束。 我正在编写一段代码,用于从大型excel文件(通常为数千行)将数据导入该表。整个导入必须在一次交易中。

可能会发生这样的情况:数千行会有一两行重复。所以我需要忽略SQLIntegrityConstraintViolationException并继续插入所有其他行。我只需要向用户显示rowNo 123是重复条目的消息。

我正在逐行读取excel文件(基于Apache POI事件),并且每行都被maped到hibernate POJO并立即保存:

public void saveRow( ExcelRow row) {
  TableRow tableRow = new TableRow(row);
  //some logic goes here
  this.session.save(tableRow);
}

我试图用

来覆盖session.save
try{
    session.save(tableRow);
}catch(SQLIntegrityConstraintViolationException e)
{
    //push the error message and continue
}

但是Netbeans喊出exception SQLIntegrityConstraintViolationException is never thrown in body of corresponding try statement

如何捕获并忽略完整性异常以继续处理数据?

我宁愿不必执行另外10K选择来检查是否存在类似的行。

1 个答案:

答案 0 :(得分:1)

Hibernate在自己的异常堆栈中包装SQL异常,通常是org.hibernate.HibernateExceptionRuntimeException。您可以捕获它,或者如果您知道它将违反约束条件,请尝试捕获ConstraintViolationException

相关问题