[英]Extending a non-abstract jpa entity class
I've been searching the web for some answers but no luck so far. 我一直在网上寻找一些答案,但到目前为止还没有运气。
I need to extend an existing entity to add some fields. 我需要扩展现有实体以添加一些字段。
Say we have a class which is already being used in the project 说我们有一个已经在项目中使用的类
@Entity
public class SampleEntity {
@Id
private Long id;
// some fields
}
And I want to create another one, that adds some additional fields. 我想创建另一个,添加一些其他字段。 Something like
就像是
@Entity
public class SampleExtendedEntity extends SampleEntity {
// some more fields
}
I am looking for a solution that would create a new db table with just those additional fields and a foreign key for SampleEntity
. 我正在寻找一种解决方案,该方案将仅使用这些其他字段和
SampleEntity
的外键创建一个新的db表。 Ideally this foreign key would also be a primary key of SampleExtendedEntity
理想情况下,此外键也应该是
SampleExtendedEntity
的主键
A very simple way to do that would be to use composition and @OneToOne
, but due to semantics I really want to use inheritance. 一种非常简单的方法是使用composition和
@OneToOne
,但是由于语义,我真的很想使用继承。 Unfortunatelly @MappedSuperclass
and @Inheritance
don't work for me, because the entity I'm extending is a class that can be (and is) used as standalone. 不幸的是,
@MappedSuperclass
和@Inheritance
对我不起作用,因为我扩展的实体是一个可以(并且)用作独立类的类。 Any suggestions would be appreciated 任何建议,将不胜感激
@Entity
public class SampleExtendedEntity extends SampleEntity {
// some more fields
int foreignKey=-1;
public SampleExtendedEntity(int key){
this.foreignKey=key;
}
public int getforeignKey(){
return foreignKey();
}
public static void main(String[] args){
SampleExtendedEntity myEntity= new SampleExtendedEntity(2);
//SampleEntity needs a getter method for ID
System.out.println(myEntity.getForeignKey()+" "+myEntity.getId());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.