Vertx executeBatch 不返回所有行

问题描述

我正在使用 vertx JDBC 客户端池并尝试向表中插入多条记录。插入成功,但没有返回插入的记录,而是只返回第一条记录。

使用 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"));
            }
        });

输出

size = 1
id = 87

表格有四列,其中一列是自动递增的,这就是为什么上面的代码有 3 列。

在这里遗漏了什么吗?

解决方法

试试这个:

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());
        }
    });