是否可以将JPA注释添加到超类实例变量中?

我正在为两个不同的表创建相同的实体。 为了使两个实体的表映射等不同,但只将其余的代码放在一个地方 – 一个抽象的超类。 最好的方法是能够在超类中注释诸如列名之类的通用内容(因为它们将是相同的),但这不起作用,因为JPA注释不是由子类inheritance的。 这是一个例子:

public abstract class MyAbstractEntity { @Column(name="PROPERTY") //This will not be inherited and is therefore useless here protected String property; public String getProperty() { return this.property; } //setters, hashCode, equals etc. methods } 

我想inheritance并仅指定特定于子项的内容,例如注释:

 @Entity @Table(name="MY_ENTITY_TABLE") public class MyEntity extends MyAbstractEntity { //This will not work since this field does not override the super class field, thus the setters and getters break. @Column(name="PROPERTY") protected String property; } 

我是否需要在子类中创建字段,getter和setter?

谢谢,克里斯

您可能希望使用@MappedSuperclass类注释MyAbstractEntity,以便hibernate将在子项中导入MyAbstractEntity的配置,您不必重写该字段,只需使用父项。 该注释是hibernate的信号,它必须检查父类。 否则它假定它可以忽略它。

以下是一些可能有所帮助的解释示例。

@MappedSuperclass:

  • 是一个方便的类
  • 用于存储子类可用的共享状态和行为
  • 不是坚持不懈的
  • 只有子类才能持久化

@Inheritance指定三种映射策略之一:

  1. 单表
  2. 加盟
  3. 每class表

@DiscriminatorColumn用于定义将用于区分子对象的列。

@DiscriminatorValue用于指定用于区分子对象的值。

以下代码导致以下内容:

在此处输入图像描述

您可以看到id字段在两个表中,但仅在AbstractEntityId @MappedSuperclass中指定。

此外,@ DiscisatorColumn在Party表中显示为PARTY_TYPE。

@DiscriminatorValue在Party表的PARTY_TYPE列中显示为Person作为记录。

非常重要的是,AbstractEntityId类根本没有持久化。

我没有指定@Column注释,而只是依赖于默认值。

如果您添加了一个扩展Party的组织实体,并且如果该实体是下一个持久化的,那么Party表将具有:

  • id = 2
  • PARTY_TYPE =“组织”

组织表第一个条目将具有:

  • id = 2
  • 与组织特定关联的其他属性值

     @MappedSuperclass
     @SequenceGenerator(name =“sequenceGenerator”, 
             initialValue = 1,allocationSize = 1)
     public class AbstractEntityId实现Serializable {

         private static final long serialVersionUID = 1L;

         @ID
         @GeneratedValue(generator =“sequenceGenerator”)
         protected Long id;

         public AbstractEntityId(){}

         public Long getId(){
            返回id;
         }
     }

     @实体
     @Inheritance(strategy = InheritanceType.JOINED)
     @DiscriminatorColumn(name =“PARTY_TYPE”, 
             discriminatorType = DiscriminatorType.STRING)
    公共类Party扩展AbstractEntityId {

        公共党(){}

     }

     @实体
     @DiscriminatorValue( “人”)
    公共类人员延伸党{

         private String givenName;
         private String familyName;
         private String preferredName;
         @Temporal(TemporalType.DATE)
        私人约会dateOfBirth;
        私人字符串性别;

         public Person(){}

         // getter&setters等

     }

希望这可以帮助 :)

将超类标记为

 @MappedSuperclass 

并从子类中删除该属性。

使用@MappedSuperclass注释您的基类应该完全符合您的要求。