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

问题描述:

我正在创建两个不同表的实体。为了使两个实体的表映射等不同,但只将其余的代码放在一个地方 - 抽象的超类。最好的情况是能够在超类中注释通用的东西,比如列名(因为它们将是相同的),但这不起作用,因为JPA注释不会被子类继承。这里有一个例子:是否可以将JPA注释添加到超类实例变量中?

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 
} 

,我想继承和唯一指定儿童专用的东西,比如注释:

@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在孩子班?

感谢, 克里斯

你可能想注释MyAbstractEntity与@MappedSuperclass类,以便休眠将导入在孩子MyAbstractEntity的配置,你会不会有覆盖领域,只需要使用父母的。该注释是休眠的信号,它也必须检查父类。否则,它认为它可以忽略它。

+3

(吹毛求疵)他只字未提休眠,是吗?他可能会使用不同的JPA提供程序。但当然你的推理适用于 – 2010-05-21 15:42:34

+0

而我实际上使用hibernate,只是忘了说这么说:) – Kristofer 2010-05-21 16:10:02

@MappedSuperclass诠释你的基类应该做的正是你想要的。

标记超类

@MappedSuperclass 

并从子类的属性。

下面是一些有助于解释的例子。

@MappedSuperclass:

  • 是一个方便的类
  • 用于存储提供给子类共享状态&行为
  • 是不是可持久化
  • 独生子女类是持久化

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

  1. 单表
  2. 加入
  3. 每个类表

@DiscriminatorColumn用来定义哪一列将用于子对象之间进行区分。

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

下面的代码结果如下:

enter image description here

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

另外,@DisciminatorColumn在Party表中显示为PARTY_TYPE。

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

非常重要的是,AbstractEntityId类根本不会持久化。

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

如果您补充说,扩大党,如果这是未来持续,那么党表将有一个组织实体:

  • ID = 2
  • PARTY_TYPE = “组织”

组织表第一项将具有:

  • id = 2
  • 特别是与组织相关
 

    @MappedSuperclass 
    @SequenceGenerator(name = "sequenceGenerator", 
      initialValue = 1, allocationSize = 1) 
    public class AbstractEntityId implements Serializable { 

     private static final long serialVersionUID = 1L; 

     @Id 
     @GeneratedValue(generator = "sequenceGenerator") 
     protected Long id; 

     public AbstractEntityId() {} 

     public Long getId() { 
      return id; 
     } 
    } 

    @Entity 
    @Inheritance(strategy = InheritanceType.JOINED) 
    @DiscriminatorColumn(name = "PARTY_TYPE", 
      discriminatorType = DiscriminatorType.STRING) 
    public class Party extends AbstractEntityId { 

     public Party() {} 

    } 

    @Entity 
    @DiscriminatorValue("Person") 
    public class Person extends Party { 

     private String givenName; 
     private String familyName; 
     private String preferredName; 
     @Temporal(TemporalType.DATE) 
     private Date dateOfBirth; 
     private String gender; 

     public Person() {} 

     // getter & setters etc. 

    } 

希望

  • 其他属性值,这有助于:)