英文:
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("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", <PREVIOUS_ID OF INSERT>)
.bind("category_id", 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) -> statement.returnGeneratedValues("id").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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论