我尝试有 2 个表,如下所示:
MISExercise(表)
身份证名称...
2个
MISInteractiveExercise(表)
身份证名称...
1个
它们必须没有相同的 ID。他们是从同一个基地继承的。我的代码是:
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class MISExerciseBase {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Integer id;
...
}
@Entity
public class MISExercise extends MISExerciseBase{
...
}
@Entity
public class MISInteractiveExercise extends MISExerciseBase{
...
}
不幸的是,我发现 MISExercise 的表和 MISInteractiveExercise 的表可以具有相同的 id。当我谷歌它时,我发现 http://openjpa.208410.n2.nabble.com/same-Id-on-mapped-superclass-td2435374.html . @Kaayan 似乎有同样的问题。但我无法从该页面获得帮助。
看来如果我使用@Entity 而不是@MappedSuperclass,那就没问题了。但为什么,什么是好方法?
最佳答案
作为您的两个类(class) MISExercise
和 MISInteractiveExersice
两者都继承自 MISExerciseBase
,
并且您已将生成策略设置为 @GeneratedValue(strategy = GenerationType.TABLE)
,
您的 id
's 不会在您的所有表中都是唯一的,而只是每个表都是唯一的。
如果您想在多个表中拥有唯一 ID,即在您的情况下 MISExercise
和 MISInteractiveExerice
,您需要将生成策略更改为 Auto
.
因此,要解决您的问题,请将您的抽象类 MISExerciseBase 更改为...
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class MISExerciseBase {
@Id
@GeneratedValue(strategy=GenerationType.AUTO) //NOTE This Change to AUTO
private Integer id;
...
}
关于hibernate - 当@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 时,为什么@MappedSuperclass 上有相同的Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20676245/