hibernate - 当@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 时,为什么@MappedSuperclass 上有相同的Id

标签 hibernate inheritance mappedsuperclass

我尝试有 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) MISExerciseMISInteractiveExersice两者都继承自 MISExerciseBase ,
并且您已将生成策略设置为 @GeneratedValue(strategy = GenerationType.TABLE) ,
您的 id 's 不会在您的所有表中都是唯一的,而只是每个表都是唯一的。

如果您想在多个表中拥有唯一 ID,即在您的情况下 MISExerciseMISInteractiveExerice ,您需要将生成策略更改为 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/

相关文章:

java - 父类(super class)中的 jXPath 查询属性

子类的 Java 构造函数

java - 为什么我不能重写和注释实体映射的 getter 方法?

java - JPA @MappedSuperclass 子类的不同 Id 计数器

hibernate - 使用 Hibernate 为用户实现 EAV 模式 -> 设置关系

Java 注解公共(public)/私有(private)范围

java - 获取 'Exception in thread "main"java.lang.IllegalArgumentException : Unknown entity: <entityClass>'

c# - NHibernate future 与 CreateMultiCriteria

C++:从 std::map 继承

c++ - 我的老师不像其他人那样进行类型转换。有谁知道他在做什么?