Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotating inherited properties for persistence

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.

like image 223
IaCoder Avatar asked Jan 06 '09 21:01

IaCoder


2 Answers

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.

like image 131
Dave L. Avatar answered Sep 22 '22 08:09

Dave L.


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(){}
}
like image 25
Vincent Ramdhanie Avatar answered Sep 19 '22 08:09

Vincent Ramdhanie