日期:2014-05-20  浏览次数:21681 次

hibernate,jdbc 批量处理问题
在线等答案 ,谢谢各位大侠了!
源代码如下:

private static final String SQL_INSERT_SPEED = "insert into Speed(speedMax,speedMin,carTag,carCode,userId,speedTime) values(?,?,?,?,?,?)";
public void insertLotSpeed(Speed speed) throws Exception {
Session session = super.getSession();
// TODO Auto-generated method stub
Transaction tx=session.beginTransaction(); //使用Hibernate事务处理
Connection conn=session.connection();
PreparedStatement stmt=conn.prepareStatement(SQL_INSERT_SPEED);
String [] carTagArray = speed.getCarTagArray();
String [] carCodeArray = speed.getCarCodeArray();
for(int i=0;i<speed.getCarTagArray().length;i++){
stmt.setInt(1, speed.getSpeedMax());
stmt.setInt(2, speed.getSpeedMin());
stmt.setString(3, carTagArray[i]);
stmt.setString(4, carCodeArray[i]);
stmt.setInt(5, speed.getUserId());
stmt.setString(6, speed.getSpeedTime());
stmt.addBatch();
}
stmt.executeBatch();
tx.commit(); //使用 Hibernate事务处理边界 
}
报错信息如下:

java.sql.BatchUpdateException: Duplicate entry '70' for key 3
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:656)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:294)
at com.zcdr.dao.hibernate.SpeedDaoImpl.insertLotSpeed(SpeedDaoImpl.java:39)
at com.zcdr.service.impl.SpeedSerivceImpl.insertLotSpeed(SpeedSerivceImpl.java:26)
at com.zcdr.servlet.SendCommandServlet.sendSpeedCommand(SendCommandServlet.java:96)
at com.zcdr.servlet.SendCommandServlet.doGet(SendCommandServlet.java:42)
at com.zcdr.servlet.SendCommandServlet.doPost(SendCommandServlet.java:66)


------解决方案--------------------
xml文件配置有误,多加了unique="true"的属性。