2

I am using vertx JDBC client pool and trying to insert multiple records to table. The insertion is done successfully but the inserted records are not returned instead only first record is returned.

Code to insert multiple record using batchExecute

List<Tuple> batch = new ArrayList<>();
batch.add(Tuple.of(36,"st","st"));
batch.add(Tuple.of(36,"st1","st1"));

pool.preparedQuery("INSERT INTO table (col1,col2,col3) VALUES($1, $2, $3) returning *").executeBatch(batch,rowSetAsyncResult -> {     
            System.out.println("size = " + rowSetAsyncResult.result().size()); // this always return 1
            for(Row row:rowSetAsyncResult.result()){
                System.out.println("id = " + row.getInteger("id"));
            }
        });

Output

size = 1
id = 87

Table has four columns and one of the column is auto-incremented, thats is why above code is having 3 columns.

Am I missing anything here?

vel
  • 173
  • 9

2 Answers2

1

I know it is so late. But I will answer it for any who faces the same issue. The code example below will fix the issue and get all rows.

  client
  .preparedQuery("INSERT INTO color (color_name) VALUES ($1) RETURNING color_id")
  .executeBatch(Arrays.asList(Tuple.of("white"), Tuple.of("red"), Tuple.of("blue")))
  .onSuccess(res -> {
    for (RowSet<Row> rows = res;rows != null;rows = rows.next()) {
      Integer colorId = rows.iterator().next().getInteger("color_id");
      System.out.println("generated key: " + colorId);
    }
  });
AYRM1112013
  • 309
  • 1
  • 7
0

Try this:

pool.preparedQuery("INSERT INTO table (col1,col2,col3) VALUES($1, $2, $3) returning id").executeBatch(batch, res -> {
        if (res.succeeded()) { // Process rows
             RowSet<Row> rows = res.result();
             int[] count = new int[] {0};
             while (rows != null) {
                 count[0]++;
                 rows.iterator().forEachRemaining(row -> {
                    System.out.println("id: " + rows.getInteger("id"));});
                 rows = rows.next();
             }
        } else {
            System.out.println("Batch failed " + res.cause());
        }
    });