Reputation: 353
I am trying to perform a self-reference mapping (parent/child-like relationship) mapping to one table.
What I am trying to have is two different entities from same table so that I could separate properties and so on. I was thinking about using a discriminator value but I can’t because my database is already defined as the following: to distinguish parent from child we have the column parent_id which is not null for a child type (parent_id is of course, the foreign key to the same table). There is no way to define discriminator value in the following way: if object is of parent type then discriminator value null child otherwise.
I was looking for solution and I am a little bit stuck. Maybe, I will end up using one entity with two properties referring to parent (not null for child, @ManyToOne) and list of child (@OneToMany null for child). But until then (the moment, I have to decide using one entity), I would like to ask if there is a work around to perform what I am trying to do.
Upvotes: 0
Views: 2371
Reputation: 7805
Another solution is to exploit special Hibernate values @DiscriminatorValue("null")
and @DiscriminatorValue("not null")
@Entity
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn("parent_id")
@DiscriminatorValue("null")
public class Parent {
...
}
@Entity
@DiscriminatorValue("not null")
public class Child extends Parent {
...
}
Upvotes: 0
Reputation: 9443
The discriminator can be a "formula". This is strictly a Hibernate feature, and not supported by JPA. You would use @org.hibernate.annotations.DiscriminatorFormula, something like:
@Entity
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorFormula( "case when parent_id is null then 'PARENT' ELSE 'CHILD' end" )
@DiscriminatorValue("PARENT")
public class Parent {
...
}
// map Child using @DiscriminatorValue("CHILD")
Upvotes: 2