Hibernate:带继承的NaturalId

时间:2014-10-30 16:39:15

标签: java hibernate inheritance hibernate-onetomany natural-key

我有以下实体(简短版):

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;
}

队列:

@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;
}

所以我有一个带有GroupOfStudents的CourseLecture。有Centuria或Cohort等不同的GroupOfStudents。但是我希望队列的数字字段是NaturalId。这将导致错误:

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

但为什么我只能在root实体上使用@NaturalId?如何在不破坏类继承的情况下解决这个问题?

1 个答案:

答案 0 :(得分:1)

好的,我完全误解了@NaturalId,主要目的是通过这个NaturalIds在表上启用查询,所以这只适用于根实体。

对于我的子实体来说,想要的是一个简单的唯一约束,这可以通过以下方式实现:

单列

@Column(unique = true)

多列

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