Search code examples
javaspring-data-r2dbcr2dbcwebflux

r2dbc validate if id exists and then insert row


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.


Solution

  • Here's a solution that only uses SQL, and isn't R2DBC specific: You can use INSERT .. SELECT to insert data only conditionally:

    INSERT INTO relation (id, rel_id)
    SELECT :id, rel_id
    FROM other_table
    WHERE rel_id = :rel_id
    

    If there is no row for :rel_id in your other table, then that statement will not insert anything.