Мне нужно получить доступ к автоматически сгенерированным данным (идентификатор, создан, 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;
}
Вы заинтересованы, есть лилучший способ добиться того, что мне нужно?