Annotate inherited properties to save

Assuming I have class A as follows:

class A{ int id; int getId(){}; void setId(int id){}; } 

And 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 that this is the Id for the organization? I tried just putting @Id on the field in A, but that didn't work. I tried to make A an entity, and that didn't work either.

+4
source share
2 answers

Assuming you don't want the superclass to represent the entity itself, you can use @MappedSuperclass in the superclass so that subclasses inherit the properties to be saved:

 @MappedSuperclass class A{ int id; @Id int getId(){}; void setId(int id){}; } 

Consider creating an abstract superclass. See this section of the document for details.

+10
source

There are several strategies you can use. Here is what 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(){} } 
+1
source

All Articles