Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT in a ONE to ONE Relationship

How to insert records in one to one relationship?

lets say i have 3 tables : table A , table B, table C

I have to insert a record into those tables which table A is referenced as the main table for primary key.

Lets just say like this:

tableB.PK = tableA.PK
tableC.PK = tableA.PK

Now,

when I am inserting records in tableB or tableC the error occurs:

Error Message: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tableB_tableA"

But when I am inserting in tableA which is the basis of the two tables' primary keys, it is ok and it increments.

How would I insert a record? Specifically in JPA.

  1. Do I need to insert into tableA first then insert in others? (Just did that and it does not work)
  2. Do I need to insert data in the tables at the same time? (How? in JPA will be good)
like image 930
bpunzalan Avatar asked May 23 '14 07:05

bpunzalan


1 Answers

Here again my comment as an answer

since you have a reference in tableB and tableC to tableA, you have to insert tableA first and retreive the generated PK. Then you can insert in any of the other tables with the retrieved ID. For JPA have a look here: How to get Id of last persisted entity using JPA

And here is an example how to achieve this in sql server: http://sqlfiddle.com/#!3/a3f62/3

this is a basic in relational databases and foreign keys, i didnt read the wiki article, but it have to mention same the thinkg: http://en.wikipedia.org/wiki/Foreign_key

like image 81
deterministicFail Avatar answered Sep 17 '22 12:09

deterministicFail