【问题标题】:Annotating inherited properties for persistence注释继承的属性以实现持久性
【发布时间】:2010-09-29 21:53:33
【问题描述】:

假设我有一个 A 类如下:

class A{
   int id;
   int getId(){};
   void setId(int id){};
}

还有一个B类如下:

@Entity
@Table(name="B")
class B extends A{
   string name;

   @Column(length=20)
   string getName(){}
   void setName(){}
}

如何注释从 A 继承的 id 字段,以便 Hibernate/JPA 知道它是 Id 为实体?我尝试简单地将@Id 放在 A 中的字段上,但这不起作用。一世 也尝试将 A 设为实体,但这也没有用。

【问题讨论】:

    标签: java hibernate jpa annotations spring


    【解决方案1】:

    假设您不希望超类本身代表一个实体,您可以在超类上使用@MappedSuperclass 让子类继承属性以实现持久性:

    @MappedSuperclass
    class A{
       int id;
       @Id
       int getId(){};
       void setId(int id){};
    }
    

    考虑将超类抽象化。有关详细信息,请参阅文档的this section

    【讨论】:

      【解决方案2】:

      您可以使用多种策略。您可以尝试以下方法:

      @Entity
      @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
      class A{
         int id;
      
         @Id @GeneratedValue
         int getId(){};
         void setId(int id){};
      }
      
      
      @Entity
      @Table(name="B")
      class B extends A{
         string name;
      
         @Column(length=20)
         string getName(){}
         void setName(){}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-25
        • 2013-10-24
        • 1970-01-01
        • 2020-02-09
        • 1970-01-01
        • 2015-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多