我有以下实体(简称):

学生小组:

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


百年纪念

@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。有不同的GroupOfStudents,例如Centuria或Cohort。但是我希望队列的数字字段为NaturalId。这将导致错误:

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


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

最佳答案

好的,我完全误解了@NaturalId,主要目的是通过此NaturalIds在表上启用查询,因此仅在根实体上工作才有意义。

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

@Column(unique = true)用于单列

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

09-11 19:42