Java 可以向超类实例变量添加JPA注释吗?
我正在为两个不同的表创建相同的实体。为了使两个实体的表映射等不同,但只有一个地方的代码的其余部分-一个抽象超类。最好的办法是能够在超类中注释通用的东西,例如列名(因为列名是相同的),但这不起作用,因为子类不会继承JPA注释。以下是一个例子:Java 可以向超类实例变量添加JPA注释吗?,java,inheritance,jpa,annotations,Java,Inheritance,Jpa,Annotations,我正在为两个不同的表创建相同的实体。为了使两个实体的表映射等不同,但只有一个地方的代码的其余部分-一个抽象超类。最好的办法是能够在超类中注释通用的东西,例如列名(因为列名是相同的),但这不起作用,因为子类不会继承JPA注释。以下是一个例子: public abstract class MyAbstractEntity { @Column(name="PROPERTY") //This will not be inherited and is therefore useless here
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吗
谢谢,
Kris用
@MappedSuperclass
注释基类应该完全符合您的要求。将超类标记为
@MappedSuperclass
然后从子类中删除属性。您可能希望使用
@MappedSuperclass
类注释MyAbstractEntity,这样hibernate将在子类中导入MyAbstractEntity的配置,而不必重写该字段,只需使用父类的。该注释是休眠的信号,它也必须检查父类。否则,它会假定它可以忽略它。下面是一个示例,其中有一些解释可能会有所帮助
@MappedSuperclass:
- 这是一个方便班
- 用于存储子类可用的共享状态和行为
- 是不持久的
- 只有子类是持久的
- id=2
- PARTY_TYPE=“组织”
- id=2
- 与组织特别相关的其他属性值
希望这有帮助:)(吹毛求疵)他没有提到冬眠,是吗?他可以使用不同的JPA提供商。当然,你的推理并不适用,我实际上在使用hibernate,只是忘了这么说:) @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. }