Hibernate和/或JDBC批处理插入/更新异常处理

时间:2014-03-26 20:12:18

标签: hibernate jdbc transactions

假设我在Hibernate的批处理操作中插入100行,类似于:

beginTx with flush mode manual;

insert 100 rows;
do 100 times {
    insert row
    commit;
}
flush;
clear;

理想情况下,这应该转换为批处理操作(因为批量大小的参数,由Hibernate设置的键等)。 但是假设批处理中的一个插入在FK约束上失败,或者其他什么。 已提交单个行,但仅在刷新期间出现问题(约束违规)。

这种情况可能吗? (我100%肯定这是到现在为止发生的事情) 如果是这样,我应该担心它,还是JDBC或Hibernate负责业务? 处理此问题的最佳方法是什么?

感谢。

- 编辑:这是例外

ERROR Caught exception while trying to flush: 
org.hibernate.exception.ConstraintViolationException: could not execute batch
    at    org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:132)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.doExecuteBatch(BatchingBatch.java:111)
at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.execute(AbstractBatchImpl.java:163)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.executeBatch(JdbcCoordinatorImpl.java:217)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:472)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:345)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1218)
...

Caused by: java.sql.BatchUpdateException: Duplicate entry '218947-449145434175721472' for key 'Unique XXX AAA and BBB'
    ...   

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '218947-449145434175721472' for key 'Unique XXX AAA and BBB'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

1 个答案:

答案 0 :(得分:1)

您的查询似乎可能与此In batch insert, how to continue inserting other rows when an error occurred in one row

重复

在那里你也可以看到答案。