Assuming I have a class A as follows:
class A{
int id;
int getId(){};
void setId(int id){};
}
And a class B as follows:
@Entity
@Table(name="B")
class B extends A{
string name;
@Column(length=20)
string getName(){}
void setName(){}
}
How can I annotate the inherited id field from A so that Hibernate/JPA knows it is the Id for the entity? I tried simply placing @Id on the field in A but this didn't work. I tried making A an entity as well and this also didn't work.
Assuming you don't want the superclass itself to represent an entity, you can use @MappedSuperclass
on the super class to have subclasses inherit the properties for persistence:
@MappedSuperclass
class A{
int id;
@Id
int getId(){};
void setId(int id){};
}
Consider making the superclass abstract. See this section of the doc for more details.
There are a number of strategies you can use. Here is something you can try:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
class A{
int id;
@Id @GeneratedValue
int getId(){};
void setId(int id){};
}
@Entity
@Table(name="B")
class B extends A{
string name;
@Column(length=20)
string getName(){}
void setName(){}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With