I got a class with a one-to-one relation. Basically, in “class A” I have a one-to-one relation to “class B”. This relation uses a primary key join column. Now my issue is as follows, if I try and create a instance of A, I cant save it because I haven’t added a instance of B to it yet. But, I cant create a instance of B because I need the id of A first.
A easy solution would be to make the ID in B the automatically generated one, so I could then create a instance of B before creating a instance of A. However, I’m sure there is a better way of doing this? 🙂
I can see in the database that hibernate created a additional index on the id column of A, which im guessing is a foreign key constraint. And I can see the the documentation that the XML version of the one-to-one mapping have a attribute to specify if the relation is constrained or not, however, the @OneToOne annotation doesnt seem to have this option? :S
It seems you have two relationships between
AandBtables (you have:Ahasa_id,b_id;Bhasb_id,a_id). To modelone to oneyou need only one relationship. Determine which table is ‘main’ and then drop column from ‘secondary’ table (should be:Ahasa_id,b_id;Bhasb_id). After that hibernate (and any other schema client) will be able to insert toBfirst, then toAwith reference toBtable.For example for egg and chicken. There are multiple relations between eggs and chickens (one chicken can laid many eggs; one egg can produce one chicken). So for the
one to onerelationship egg-produces-chicken, it is reasonable to haveparent_egg_idcolumn inchickentable, so an egg can be created first and then a chicken with reference to that egg.Hibernate mapping could look like the following:
In Chicken class:
In Egg class:
Update:
The same thing as
constrainedin xml,optionalproperty inOneToOneinterface will do. It is defaulted to true, so the relationship is nullable by default.According to your comments rows to
Aare inserted first. I would consider having dependency fromBtoA, not fromAtoB. In this case to create item inAthen inB, twoinsertstatements are required (with relation fromAtoB– additionalupdate Astatement is required.).