I have following sql query with r2dbc:
client.sql("INSERT INTO relation(id,rel_id) "
+ "VALUES(:id,:rel_id)")
.filter((statement, executeFunction) -> statement.returnGeneratedValues("id").execute())
.bind("id", id)
.bind("rel_id", rel_id)
.fetch()
.first()
.subscribe(
data -> log.info("inserted data : {}", data),
error -> log.error("error: {}", error)
);
And my problem is thet rel_id is constraint(foreign key) to another table Person. So, I would like to check if rel_id exists in table Person and if exists then insert into relation. Or maybe throw some exception if not founded in Person table. I don't know what is prefered way for this case.
Here's a solution that only uses SQL, and isn't R2DBC specific: You can use
INSERT .. SELECT
to insert data only conditionally:If there is no row for
:rel_id
in your other table, then that statement will not insert anything.