获取Lambda函数的返回值

usr*_*_11 5 java postgresql jooq

我有一个使用 lambda 实现的函数调用,它使用 jooq 库在 postgres 数据库中插入一行。

下面是代码:

  dslContext.transaction(
    c -> {
        this.postgresService.insertData(c, table, map);
    });
Run Code Online (Sandbox Code Playgroud)

其中 c 类型为 org.jooq.Configuration。

该代码工作正常并在表中插入一条记录并返回插入的记录。如何访问 lambda 函数返回的主键。

这是 insertData 的函数:

public Record insertData(
        Configuration configuration, Table<? extends Record> table, Map<TableField<? extends Record, ?>, Object> map
    )
    {
        return DSL.using(configuration)
            .insertInto(table)
            .set(map)
            .returning()
            .fetchOne();
    }
Run Code Online (Sandbox Code Playgroud)

dig*_*ise 6

只需使用transactionResult

String primaryKey = dslContext.transactionResult(
  (Configuration c) -> {
    return this.postgresService.insertData(c, table, map);
  });
Run Code Online (Sandbox Code Playgroud)


小智 1

您可以创建一个包装类来存储检索到的值:

class PrimaryKeyWrapper{
    Record primaryKey;

    public void setPrimaryKey(Record primaryKey) {
      this.primaryKey = primaryKey;
    }

    public Record getPrimaryKey() {
     return primaryKey;
    }
  }
Run Code Online (Sandbox Code Playgroud)

并使用该类的实例来从 lambda 函数内部存储该值:

PrimaryKeyWrapper primaryKeyWrapper = new PrimaryKeyWrapper();

dslContext.transaction(
c -> {
    Record primaryKey = this.postgresService.insertData(c, table, map);
    primaryKeyWrapper.setPrimaryKey(primaryKey);

});
Run Code Online (Sandbox Code Playgroud)

最后可以从外部获取值:

primaryKeyWrapper.getPrimaryKey();
Run Code Online (Sandbox Code Playgroud)