2

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

In other words, they both have 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?

xiaohan2012
  • 9,870
  • 23
  • 67
  • 101

2 Answers2

3

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.

sudmong
  • 2,036
  • 13
  • 12
1

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;
mAu
  • 2,020
  • 1
  • 14
  • 27
  • 1
    Disabling foreign key constraints is usually a very bad idea. If you do do it, then at least put the whole lot in a transaction. – Mike Jul 23 '11 at 11:52
  • Of course you should run it inside a transaction. But i don't see any other way to achieve the required without disabling the foreign key checks ... – mAu Jul 23 '11 at 11:55
  • Sorry, ignore it. I am mistaking something – xiaohan2012 Jul 23 '11 at 12:07