使用executeBatch()插入列表时返回数据

时间:2018-12-18 07:27:26

标签: java postgresql jdbc

插入数据列表时,我必须访问自动生成的数据(标识,创建的,last_modified ...)。由于列表可能很大,因此我使用statement.executeBatch()将所有内容添加到包中。但是,这样一来,我就失去了利用returning语句的机会。

我目前正在执行以下操作以获取数据:

public boolean store(Connection connection, List<WorkPlace> list) throws SQLException {
    String query =
            "insert into work_places (merchant_id, name, description) values (?, ?, ?)";

    try(PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
        for(WorkPlace workPlace: list) {
            statement.setLong(1, workPlace.getMerchantId());
            statement.setString(2, workPlace.getName());
            statement.setString(3, workPlace.getDescription());

            statement.addBatch();
        }

        statement.executeBatch();

        try(ResultSet rs = statement.getGeneratedKeys()) {
            List<Long> ids = new ArrayList<>();

            while (rs.next()) {
                ids.add(rs.getLong(1));
            }

            query =
                    "select * from work_places where id = any (?)";

            try(PreparedStatement statement1 = connection.prepareStatement(query)) {
                statement1.setArray(1, connection.createArrayOf("integer", ids.toArray()));

                try(ResultSet rs1 = statement1.executeQuery()) {
                    list.clear();

                    while (rs1.next()) {
                        list.add(getWorkPlace(rs1));
                    }
                }
            }
        }
    }

    return true;
}

您是否有兴趣,有没有更好的方法来满足我的需求?

1 个答案:

答案 0 :(得分:1)

PostgreSQL JDBC驱动程序中生成的键实现使用RETURNING *,它将返回表中的所有列。因此,如果您可以在执行批处理后以这种方式检索生成的ID,那么您还应该能够从相同的getGeneratedKeys结果集中检索其他列。