In my project I have a POJO called BaseEntity as shown below.
class BaseEntity{
private int id;
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
}
And a set of other POJO entity classes like Movie, Actor,...
class Movie extends BaseEntity{
private String name;
private int year;
private int durationMins;
//getters and setters
}
I'm using BaseEntity only for using it as a place holder in some interfaces. I never have to store a BaseEntity object. I have to store only the entity objects extended from BaseEntity. How should I annotate these classes so that I get one table per entity extended from the BaseEntity. For movie it should be like (id, name, year, durationMins).
@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. @Id annotation marks the identifier for this entity.
@Id and @GeneratedValue Annotations Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure.
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table.
I found the answer in a totally unrelated post. I just have to annotate BaseEntity as @MappedSuperclass. The following code done what I needed.
@MappedSuperclass
class BaseEntity {
@Id
private int id;
//getters and setters.
}
@Entity
class Movie extends BaseEntity {
@Column
private String name;
@Column
private int year;
@Column
private int durationMins;
//getters and setters
}
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