I have a scenario where I have a entity hierarchy structure implemented in hibernate.
It is InheritanceType.JOINED
Parent class:
@Entity
@Table(name = "LOY")
@Inheritance(strategy=InheritanceType.JOINED)
public class Loy implements Serializable
Child class boundary
@Entity
@Table(name = "LOY_BOUNDARY")
@PrimaryKeyJoinColumn(name="ID")
public class LoyBoundary implements Serializable
Child class percentage
@Entity
@Table(name = "LOY_PERCENTAGE")
@PrimaryKeyJoinColumn(name="ID")
public class LoyPercentage implements Serializable
I have a Customer entity class which is linked to the Loy entity class in a @ManyToOne.
The Customer can only be linked to one Loy at a time.
What I want to achieve is that I want to query the Customer class with unique id (passport number) and then get The Loy for the specific Customer through the @ManyToOne mapping in the Customer entity.
The problem that I’m sitting with is that I do not know which subclass of Loy is linked to the Customer.
- I can go instanceOf to get the specific subclass but I want to try and avoid it.
- I can also add a visitor pattern in the subclass entity, but not sure if this is best practice.
I would go with a visitor. Using
instanceofwon’t work if theManyToOneis lazy-loaded, because the actual type of the Loy won’t be any of your subclasses, but a Hibernate proxy extending the Loy class. Indeed, Hibernate has no way to know, from the ID of the loy in the customer, which kind of Loy it refers to.And a visitor is more OO and cleaner anyway.