Spring Data JDBC save to two tables

429 views Asked by At

How to save an entity to two tables at the same time using Spring Data JDBC?

class MyEntity {
  /* to be saved in table #1 */
  int ID; /* auto-generated in table #1 */
  String name;
  /* to be saved in table #2 */
  int titleID; /* auto-generated in table #2 */
  String title;
}

I am new to Spring. It took me two days to find out how to do INNER JOIN query using Spring Data JDBC.

1

There are 1 answers

0
Jens Schauder On

There is no special support in Spring Data JDBC for this.

You can do one of the following:

  1. create an updatable view on the two tables, that joins the two tables and map your entity to that view. In order to be able to update both tables you might have to add triggers to the view, depending on the capabilities of your database.

  2. You might split the entity into two with a 1:1 relationship with each being persisted in one table.