Reputation: 4267
I know my title is not clear, but I don't know how to explain my question with few words.
I have two classes with a bidirectional mapping. Image.class
:
@Entity
@Table(name = "image")
public class Image{
@Id
@Column(name = "id")
@GeneratedValue
Long id;
@OneToOne(targetEntity = Father.class)
@JoinColumn(referencedColumnName = "id", name="father")
@Size(min = 1, max = 11)
Father father;
}
and Father.class
:
class Father{
@Id
@Column(name = "id")
@GeneratedValue
Long id;
@OneToOne(mappedBy = "father")
Image pic;
}
Now, I'd like to use Image.class
as field of other classes. Let's say I have Mother.class
class Mother{
@Id
@Column(name = "id")
@GeneratedValue
Long id;
@OneToOne(mappedBy = "mother")
Image pic;
}
My question is: how should I edit the "mapping" of Image.class
?
Of course Image.class
cannot have a field like Father father
, since in the last scenario Image.class
is a field of Mother.class
and is not a field of Father.class
.
I remember that there was I way that allow you to save, in a single table, an Entity
that can be mapped by many different Entities
. I remember that I needed to add a field in the table that distinguishes wheter Image.class
is "bound" to Father.class
or Mother.class
.
I'm no more able to find that documentation on the internet.
Upvotes: 3
Views: 513
Reputation: 88707
Note that "field" is not the right term to describe a relation. Father
and Mother
would have a relation to Image
and this could be unidirectional, i.e. Image
wouldn't know which entity it belongs to.
This probably is the most sensible way to go and if there are no good reasons to require a bidirectional relation I'd suggest you go the unidirectional route. To make the relation unidirectional you'd have to make Mother
and Father
the owning side, i.e. put the image id into their tables and remove the mappedby
from their @OneToOne
while removing the mapping from Image
entirely.
If you really need to know that and need Hibernate to be able to navigate the relation then you'd have to use a common super class (also needs to be an entity even if there are no instances) and probably table-per-class inheritance.
Besides that you could store information about who is related to the image in Image
itself and do the lookup manually.
Upvotes: 4