在 Lambda 函数中获取返回值

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


下面是代码:


  dslContext.transaction(

    c -> {

        this.postgresService.insertData(c, table, map);

    });

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


代码正常工作并在表中插入一条记录并返回插入的记录。如何从 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();

    }


米脂
浏览 279回答 2
2回答

肥皂起泡泡

您可以创建一个包装类来存储检索到的值:class PrimaryKeyWrapper{&nbsp; &nbsp; Record primaryKey;&nbsp; &nbsp; public void setPrimaryKey(Record primaryKey) {&nbsp; &nbsp; &nbsp; this.primaryKey = primaryKey;&nbsp; &nbsp; }&nbsp; &nbsp; public Record getPrimaryKey() {&nbsp; &nbsp; &nbsp;return primaryKey;&nbsp; &nbsp; }&nbsp; }并使用该类的实例从 lambda 函数内部存储此值:PrimaryKeyWrapper primaryKeyWrapper = new PrimaryKeyWrapper();dslContext.transaction(c -> {&nbsp; &nbsp; Record primaryKey = this.postgresService.insertData(c, table, map);&nbsp; &nbsp; primaryKeyWrapper.setPrimaryKey(primaryKey);});最后,您可以从外部获取值:primaryKeyWrapper.getPrimaryKey();

潇潇雨雨

只需使用transactionResult:String primaryKey = dslContext.transactionResult(&nbsp; (Configuration c) -> {&nbsp; &nbsp; return this.postgresService.insertData(c, table, map);&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java