[Solved] [Problem] Referencing two objects with OneToOne relation
Joined: Apr 18, 2009
I am working on a project with Hibernate and this is my situation. I have a base class A and two classes B and C that extend it. This works fine as far as I know with the following code:
So, Hibernate creates a table for every class, that's A, B and C. It is the "Joined subclasses" method of the Hibernate Annotations Reference Guide. This seems to work fine as mentioned above.
Now, I have a class named Wrapper which has a property of class B and C and only one, like this:
I thought about realizing a OneToOne relation (with shared primary keys) between class B and Wrapper and C and Wrapper using something like explained here but I was not able to achieve it or was not sure if it was correct. Than I thought about using just a foreign key for the classes B and C pointing to the Wrapper with a unique constraint but I do not know how.
Another idea would be to set the id of the instances of the classes B and C to the id of the Wrapper when setting instance_B and instance_C. I do not know if this is the right way and I am very doubtful about that.
I hope that this is comprehensible and that somebody can help me out of this. Perhaps somebody has a better idea than I had.
With best regards
Joined: Apr 18, 2009
Ok, I finally got it myself...
The Reference Documentation states that you can also establish a OneToOne relation by adding foreign keys. For my case this would be adding foreign keys to the table of the Wrapper for instance_B and instance_C. So, those foreign keys reference to a row in the tables B and C (more exact to the table of A because B and C share the primary key with A because of inheritance).
Doing this like explained in the hibernate documentation for the annotations you have to put some annotations above the Getter of your property (here the getters of instance_B and instance_C). Like this:
This does not work (in my case). Hibernate just put the entries as a binary type into a column of the DB.
Now, I wrote the annotations shown in the code directly above the declaration of the two properties:
This finally works for me. Hibernate takes the primary key out of the associated rows of the tables of B and C and uses them as foreign keys in the columns name_of_fk_B and name_of_fk_C of the rows of the table Wrapper.
Is there anybody else experiencing those problems?