Home > Software engineering >  How to insert into a single table from multiple tables jpa
How to insert into a single table from multiple tables jpa

Time:10-10

I have four different tables (t1, t2, t3, t4) And I want to take data from three of those tables and insert into the fourth table how do I do this in JPA?

Is this right?

"INSERT INTO t4 (fname, lname) VALUES (:fname, :lname) FROM t1 INSERT INTO t4 (age, address) VALUES (:age, :address) FROM t2 INSERT INTO t4 (phone) VALUES (:phone) FROM t3"

Please how do I write the query correctly?

And then:

query.setParameter ("fname", fname);

CodePudding user response:

First, you have to create 4 entity classes and then declare the parameters you want, after that, you have to map the other three entities from which you want to insert data to the one in which you want to insert. You can take the reference by the below link:

https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables

CodePudding user response:

You can probably use something like that:

INSERT INTO t4( fname, lname, age, address, phone )
SELECT t1.fname, t1.lname, t2.age, t2.address, t3.phone
FROM t1
INNER JOIN t2 ON t2.Id = t1.Id
INNER JOIN t3 ON t3.Id = t1.Id
  • Related