我有以下实体(简短版本):
学生组:
@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;
}
所以我和一群学生一起进行类(class)讲座。有不同的学生组,例如 Centuria 或 Cohort。但我希望 Cohort 的数字字段是 NaturalId。这将导致错误:
AnnotationException: @NaturalId only valid on root entity (or its @MappedSuperclasses)
但是为什么我只能在根实体上使用@NaturalId?如何在不破坏类继承的情况下解决这个问题?
最佳答案
好吧,我完全误解了@NaturalId
,主要目的是在表上启用此 NaturalId 的查询,因此这只适用于根实体才有意义。
想要的是我的子实体的简单唯一约束,这可以通过以下方式实现:
@Column(unique = true)
单列
@Table(name = "centuria", uniqueConstraints = { @UniqueConstraint(columnNames = { "cohort", "maniple", "letter"}) })
对于多列
关于java - Hibernate:带有继承的 NaturalId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26658590/