javahibernateinheritancehibernate-onetomanynatural-key

Hibernate: NaturalId with inheritance


I have following Entities (short version):

GroupOfStudents:

@Entity
@Table(name = "group_of_students")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AGroupOfStudents extends AModel {
}

Centuria:

@Entity
@Table(name = "cohort")
@PrimaryKeyJoinColumn(name = "id")
public class Cohort extends AGroupOfStudents {

    @Column(nullable = false)
    // @NaturalId <- here is the problem
    private int number;
}

Cohort:

@Entity
@Table(name = "centuria")
@PrimaryKeyJoinColumn(name = "id")
public class Centuria extends AGroupOfStudents {

    @Column(nullable = false)
    // @NaturalId <- here is the problem
    private int cohort;


    @Column(nullable = false)
    // @NaturalId <- here is the problem
    private char maniple;
}

So I have a CourseLecture with a GroupOfStudents. There are different GroupOfStudents like Centuria or Cohort. But I want the number field of the Cohort to be a NaturalId. this will cause the error:

AnnotationException: @NaturalId only valid on root entity (or its @MappedSuperclasses)

but why can I use @NaturalId only on root entities? How can I solve this problem without breaking up my class inheritance?


Solution

  • Ok ,I totally misunderstood @NaturalId, the main purpose is to enable queries by this NaturalIds on the table, so this working only on root entities makes sense.

    what a wanted was a simple unique constraint for my sub entities, this can be achieved by:

    @Column(unique = true) for a single column

    @Table(name = "centuria", uniqueConstraints = { @UniqueConstraint(columnNames = { "cohort", "maniple", "letter" }) }) for multiple columns