We are using the Multi-Tenancy in the following structure, where Dog
and Cow
belong to different schema and NEVER co-exist in the same schema:
Parent Class, which is in both schema
HOME
andFARM
:@Entity @Inheritance(strategy = InheritanceType.JOINED) ... public class Animal implements Serializable {...}
Child Class 1, which is in schema
HOME
:@Entity @PrimaryKeyJoinColumn(name = "ANIMAL_ID") ... public class Dog extends Animal {...}
Child Class 2, which is in schema
FARM
:@Entity @PrimaryKeyJoinColumn(name = "ANIMAL_ID") ... public class Cow extends Animal {...}
In this way, when we fetch the Animal entity by different repository, it will fetching only the corresponding child class, i.e., from DogRepository, it will do SELECT * FROM ANIMAL a JOIN DOG d ON a.ID = d.ANIMAL_ID
, which essentially does SELECT * FROM HOME.ANIMAL a JOIN HOME.DOG d ON a.ID = d.ANIMAL_ID
, and this is exactly what we want.
Now, inside the parent class, we have a field which has a bidirectional @OneToMany and @ManyToOne relationship:
Inside
Animal.class
:@OneToMany( fetch = FetchType.EAGER, mappedBy = "animal", cascade = {CascadeType.PERSIST, CascadeType.MERGE}) private List<AnimalRelation> relationships;
Inside
AnimalRelation.class
:@ManyToOne @JoinColumn(name = "ANIMAL_ID") private Animal animal;
Here comes the issue: when Animal entity has AnimalRelation inside, with the current structure, Hibernate is not able to know which child class it needs, i.e., even from DogRepository, it will do SELECT * FROM ANIMAL a LEFT JOIN DOG d ON a.ID = d.ANIMAL_ID JOIN COW c ON a.ID = c.ANIMAL_ID
. But this causes issue as Dog
and Cow
are not in the same schema, so we get error: ORA-00942: table or view does not exist
.
Here is the question: how can we require the subentity @ManyToOne to either joining Animal with Dog only, or fetching Animal only?