'Hibernate - @ManyToOne on Entities that extends from Abstract class
I have a similar structure already existing in my database and it has many data:
@MappedSuperclass
public abstract class Person {
@Id
Long id;
@Column(name="COMMONFIELD")
String commonField;
}
@Entity
@Table(name = "WOMAN")
public class Woman extends Person {
.....
}
@Entity
@Table(name = "MAN")
public class Man extends Person {
.....
}
This code will work with two different tables WOMAN and MAN where both will contain the common fields defined in the abstract class Person.
Now I will like to have a class Car that has an owner which can be either a woman or a man. A person can also be the owner of several cars. So I declare it like this:
@Entity
@Table(name = "CAR")
public class Office {
....
@ManyToOne
@JoinColumn(name = "IDPERSON")
Person owner;
}
The issue I encounter is that I cannot create an attribute linked to a Mapped-Superclass.
Of course, I could solve this issue simply by defining Person as an entity and declaring it to be InheritanceType.SINGLE_TABLE and Woman and Man with a discriminator this way they could share the same table and it will work. However, this solution is not possible for me because the data is already there and there are many dependencies from it, so I cannot change the WOMAN or MAN table.
Is there a way to use a discriminator in this case too, so that Hibernate will know in which table it has to look for the person?
Thank you very much in advance.
Solution 1:[1]
So I couldn't find any way to tell hibernate to use a discriminator on a specific attribute.
So what I did, I created a Gender Enum
enum Gender {
WOMAN, MAN;
}
And I added it as an attribute of a Car. I also wired the woman and the man service and created a getter method for the owner that will decide which service to use based on gender.
@Entity
@Table(name = "CAR")
public class Office {
....
@Column(name = "PERSONID")
Long personId;
@Column(name = "GENDER")
Gender gender;
@Autowired
@Transient
WomanService womanService;
@Autowired
@Transient
ManService manService;
Optional<Person> getOwner(){
switch(gender){
case WOMAN: return womanService.findById(personId);
case MAN: return manService.findById(personId);
default: return Optional.empty();
}
}
}
I'm aware this solution sucks but it's the best I could come up with to avoid redefining other entities.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | César Castro Aroche |
