【问题标题】:why same Id on @MappedSuperclass when @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)为什么 @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 时 @MappedSuperclass 上的 Id 相同
【发布时间】:2013-12-19 07:58:43
【问题描述】:

我尝试有2个表,如下:

MISExercise(表格)


ID 名称 ...

2个


MISInteractiveExercise(表)


ID 名称 ...

1b


它们不能有相同的 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,似乎会很好。但是为什么,有什么好的方法呢?

【问题讨论】:

    标签: hibernate inheritance mappedsuperclass


    【解决方案1】:

    由于您的类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; 
    
        ...
    }
    

    【讨论】:

    • 正如stackoverflow.com/questions/3154649/… 所说,它不能使用AUTO。但是我只是尝试使用AUTO,似乎还可以。所以我很困惑。
    • 如果您想为每张桌子设置唯一的 ID,请坚持使用现有的 ID。但是,如果您想要唯一的 id(即两个表都使用相同的全局序列生成器,则使用 AUTO)。
    • 好的,谢谢。但是当我使用@Entity 替换@MappedSuperclass 时有什么区别吗?当我查看我的数据库时,它也不会生成表 MISExerciseBase。
    • 我仍然对链接stackoverflow.com/questions/3154649/… 感到困惑。当我google它时,我发现类似的答案发生了很多次,都说在使用策略InheritanceType.TABLE_PER_CLASS时,你只能使用GenerationType.TABLE。有什么想法吗?
    • 如果使用@MappedSuperclass,则不会创建数据库表。使用@Entity时,生成了对应的db表。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-28
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 2014-04-22
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多