当@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)时为什么@MappedSuperclass上的相同ID

时间:2013-12-19 07:58:43

标签: hibernate inheritance mappedsuperclass

我尝试有两个表,如下所示:

MISExercise(表)


ID NAME ...

2 a


MISInteractiveExercise(表)


ID NAME ...

1 b


他们必须没有相同的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,它会很好。但是为什么,以及有什么好方法呢?

2 个答案:

答案 0 :(得分:3)

由于您的课程MISExerciseMISInteractiveExersice均来自MISExerciseBase, 并且您已将生成策略设置为@GeneratedValue(strategy = GenerationType.TABLE), 您的id在所有表中都不会是唯一的,但每个表只能是唯一的。

如果您希望在多个表格中拥有唯一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; 

    ...
}

答案 1 :(得分:0)

我遇到了类似的问题。通过将其添加为类级别的注释,为我修复了此问题:

@SequenceGenerator(initialValue = 1, name = "idgen", sequenceName = "parentseq", allocationSize = 1)

您无需指定所有这些内容,但重要的部分是sequenceName,并确保子类使用与父类相同的子类。