Java的r2dbc客户端执行SQL并使用返回的ID进行下一步执行。

huangapple go评论73阅读模式
英文:

Java r2dbc client execute sql and use returned id for next execute

问题

我使用r2dbc客户端与postgresql并且我想在一个事务中调用两次插入操作使用第一个查询的id),示例如下

client.execute("INSERT INTO place(id, city) VALUES(:id, :city)")
      .bind("id", "nextval('place_id_seq')")
      .bind("city", place.getCity())
      .fetch().rowsUpdated())
      )
      .then(client.execute("INSERT INTO place_category VALUES (:place_id, :category_id);")
        .bind("place_id", <第一个插入的ID>)
        .bind("category_id", place.getCategoryId())
        .fetch().rowsUpdated())
      .then();

我不知道如何获取第一个插入的@Id <PREVIOUS_ID OF INSERT>
英文:

I use r2dbc client with postgresql and I would like to call in one transaction 2 inserts(use id of first query) like:

      client.execute(&quot;INSERT INTO place(id,city) VALUES(:id, :city)&quot;)
    .bind(&quot;id&quot;, &quot;nextval(&#39;place_id_seq&#39;)&quot;)
    .bind(&quot;city&quot;, place.getCity())
    .fetch().rowsUpdated())
    )
    .then(client.execute(&quot;INSERT INTO place_category VALUES (:place_id, :category_id);&quot;)
      .bind(&quot;place_id&quot;, &lt;PREVIOUS_ID OF INSERT&gt;)
      .bind(&quot;category_id&quot;, place.getCategoryId())
      .fetch().rowsUpdated())
    .then();

I don't know how to get @Id of first insert <PREVIOUS_ID OF INSERT>

答案1

得分: 2

 .filter((statement, executeFunction) -> statement.returnGeneratedValues("id").execute())

查看我的保存示例查询示例

还有一个用于演示将它们连接在一起的Junit测试用例

顺便说一下:我在这些示例中使用的是Spring 5.3中的DatabaseClient。

英文:

In the first statement, add an extra filter to return the id fields.

 .filter((statement, executeFunction) -&gt; statement.returnGeneratedValues(&quot;id&quot;).execute())

Check my example of Save and Query.

And there is a JUnit test case for demo connectting them together.

BTW: I was using the DatabaseClient in Spring 5.3 for these samples.

huangapple
  • 本文由 发表于 2020年10月15日 23:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64374730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定