Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Annotation using base entity

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).

like image 781
Thomas Avatar asked Sep 12 '13 12:09

Thomas


People also ask

What is entity annotation in hibernate?

@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.

What are the annotations used in entity class?

@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.

What is the use of @table annotation?

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.


1 Answers

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
}
like image 56
Thomas Avatar answered Oct 18 '22 15:10

Thomas