Hibernate抛异常Could not execute JDBC batch update

用Hibernate插入数据时(save(...))出现这个异常:

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
 at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
 at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
 at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
 at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
 at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
 at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
 at com.smart.TestautoHome.save(TestautoHome.java:127)
 at com.smart.test.main(test.java:10)
Caused by: java.sql.BatchUpdateException: 批次处理0insert into public.testauto (name, id) values (smart, 0)失败,调用getNextException查看原因。
 at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2533)
 at org.postgresql.core.v3.QueryExecutorImpl$1.handleError(QueryExecutorImpl.java:401)
 at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1316)
 at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:349)
 at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2670)
 at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
 at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
 ... 9 more

发现原来是因为利用Hibernate Tools导出的hbm映射文件中,没有设定对应数据库表的自增主键造成。导出的的hbm文件如下:

xml version="1.0" ?>
DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>

< hibernate-mapping >
    
< class  name ="com.smart.Testauto"  table ="testauto" >
        
< id  name ="id"  type ="int" >
            
< column  name ="id"   />
            
< generator  class ="assigned"   />
        
id >
        
< property  name ="name"  type ="string" >
            
< column  name ="name"  length ="50"   />
        
property >
    
class >
hibernate-mapping >

注意到,数据库里testauto表的主键id是自增的,而在上面的映射文件里是:<generator class="assigned" />

只要把 assigned 改成 increment 就可以了~

你可能感兴趣的:(数据库)