代码之家  ›  专栏  ›  技术社区  ›  James Adams

如何从BatchUpdateException中找到有问题的插入?

  •  2
  • James Adams  · 技术社区  · 14 年前

    当我有一个BatchUpdateException作为唯一约束冲突的结果时,有没有一种方法可以让我确定批插入中哪个记录是冲突的?例如,假设我正在通过调用PreparedStatement.executeBatch文件()并捕获BatchUpdateException,它的原因是“ORA-00001:unique约束”(ABC系统123)“违反”。当使用Eclipse进行调试时,我可以从这个异常中获得尽可能多的信息,但是我想找出哪个实际插入导致了对unique约束的违反。我有办法找到这些信息吗?

    public void batchInsert(final Collection<MyObject> objectCollection)
    {
        try
        {
            if (connection == null)
            {
                connection = getJdbcTemplate().getDataSource().getConnection();
            }
    
            // get the last entity ID value so we can know where to begin
            Long entityId = getJdbcTemplate().queryForLong("SELECT MAX(" + MyObject.ID_COLUMN_NAME +
                                                           ") FROM " + MyObject.TABLE_NAME);
            entityId++;
    
            // get a date to use for the created and updated dates
            Date now = new Date(new java.util.Date().getTime());
    
            // set auto commit to false so we can batch save without committing each individual insert
            connection.setAutoCommit(false);
    
            // create the prepared statement
            String insertSql = "INSERT INTO " + MyObject.TABLE_NAME + " (" +
                               MyObject.ID_COLUMN_NAME + ", VALUE_1, VALUE_2) " +
                               "VALUES (?, ?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
    
            // add a batch entry for each of the SurfaceMetObservations objects
            for (MyObject object : objectCollection)
            {
                preparedStatement.setLong(1, entityId);
                preparedStatement.setBigDecimal(2, object.getValue1());
                preparedStatement.setBigDecimal(3, object.getValue2());
                preparedStatement.addBatch();
                entityId++;
            }
    
            int updateCounts[] = preparedStatement.executeBatch();
            preparedStatement.close();
            if (confirmUpdateCounts(updateCounts))
            {
                connection.commit();
            }
            else
            {
                connection.rollback();
                throw new RuntimeException("One or more inserts failed to execute.");
            }
        }
        catch (SQLException ex)
        {
            throw new RuntimeException(ex);
        }
    }
    

    我正在使用Spring的JdbcTemplate和一个Oracle11g数据库,以备不时之需。

    --詹姆斯

    1 回复  |  直到 13 年前
        1
  •  3
  •   Vineet Reynolds    14 年前

    来自 BatchUpdateException :

    未能正确执行和 驾驶员可能会或可能不会继续 处理中的其余命令 批处理。如果司机继续 处理失败后,数组 方法返回 每个命令都有一个元素 在错误之前成功。在 处理命令,数组元素 对于任何失败的命令 Statement.EXECUTE\u失败.