是否可以将 JPA 注释添加到超类实例变量? [英] Is it possible to add JPA annotation to superclass instance variables?

查看:23
本文介绍了是否可以将 JPA 注释添加到超类实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为两个不同的表创建相同的实体.为了对两个实体进行不同的表映射等,但仅将其余代码放在一个地方 - 一个抽象超类.最好的办法是能够在超类中注释通用的东西,例如列名(因为它们是相同的),但这不起作用,因为 JPA 注释不是由子类继承的.下面是一个例子:

I am creating entities that are the same for two different tables. In order do table mappings etc. different for the two entities but only have the rest of the code in one place - an abstract superclass. The best thing would be to be able to annotate generic stuff such as column names (since the will be identical) in the super class but that does not work because JPA annotations are not inherited by child classes. Here is an example:

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
}

我想继承并且只指定特定于孩子的东西,比如注释:

Which I would like to inherit and only specify the child-specific stuff, like annotations:

@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 吗?

Any ideas or will I have to create fields, getters and setters in the child classes?

谢谢,克里斯

推荐答案

你可能想用 @MappedSuperclass 类来注释 MyAbstractEntity,这样 hibernate 就会在 child 中导入 MyAbstractEntity 的配置,你就不会'不必覆盖该字段,只需使用父字段.该注释是休眠的信号,它也必须检查父类.否则它认为它可以忽略它.

You might want to annotate MyAbstractEntity with @MappedSuperclass class so that hibernate will import the configuration of MyAbstractEntity in the child and you won't have to override the field, just use the parent's. That annotation is the signal to hibernate that it has to examine the parent class too. Otherwise it assumes it can ignore it.

这篇关于是否可以将 JPA 注释添加到超类实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆