开发者

how to perform one-to-one relational insertion in database

I am using Mysql. And I have two tables which are one-to-one related with each other.

In other words, they both h开发者_运维技巧ave a foreign key constraint referencing the primary key of the other table.

If I try to insert one record for each table, in which each record references the other. like:

The Mysql database will prevent such operation, because of the one-to-one foreign key constraint.

It is like the chicken-egg problem.

However, I noticed that in Java hibernate, such operation can be done in case two entity classes are one-to-one related.

How can that be done in Hibernate, because I notice that the two insertions(from Hibernate debug messages) are separated as I have done. So there is nothing special.

Or how can I force one record to be inserted even if the record it should referencing does not yet exist?


Put null value for one of the referenced columns, ref columns do allow null values.Later once you insert record in the referenced column, you can update the column.


You could try to disable the foreign key checks by running SET foreign_key_checks = 0 immediately before your two insert querys and immediately after your querys, enable the foreign key checking by executing SET foreign_key_checks = 1.

More information about foreign key constraints.

mysql > SET foreign_key_checks = 0;
mysql > INSERT INTO t1 (t2_id) VALUES (1);
mysql > INSERT INTO t2 (t1_id) VALUES (1);
mysql > SET foreign_key_checks = 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜