0

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.

aslan
  • 253
  • 1
  • 4
  • 13

2 Answers2

2

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")
Steve Ebersole
  • 9,339
  • 2
  • 48
  • 46
  • Thanks for your answer. I was not aware of that feature until now. It is exactly what I was looking for. So far, we were only allowed to use Hibernate features that are supported by JPA this could be the exception, I hope. Anyway, I think from now on, I am gonna use this feature on my personal project. Again, thank you! – aslan May 31 '12 at 06:19
0

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 {
    ...
}
xmedeko
  • 7,336
  • 6
  • 55
  • 85