Search code examples
mysqldatabasehibernateone-to-oneinsertion

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 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?


Solution

  • 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.