views:

212

answers:

3

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.

+5  A: 

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.

Dave L.
A: 

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(){}
}
Vincent Ramdhanie
A: 

I have an added complication of class A being in a separate maven project. How do I solve this?