Thursday, June 20, 2013

JPA-Hibernate - Inheritance - Mapped Superclass

Most of the time, when we are developing an application we will use the concept called Inheritance, there will be a chance, where we need to abstract out the common properties to a separate class and extend it in our current class. Lets see how we are going to achieve this in hibernate or jpa.

Below is the initial entity (class), before we apply our inheritance, This entity(class) has three columns (properties), let say property id and name will be used
considerably throughout my application, in many entity (class), so lets abstract out the id and name from the Expense (entity) to new class name Base.

@Entity
@Table(name="Expense")
public class Expense 
{
 
 @Id
 @Column(name="ID")
 @GeneratedValue
 private int id;
 
 @NotBlank(message = "Name should not be empty")
 @Column(name="NAME")
 private String name; 

  
 @NotBlank(message = "Amount should not be empty")
 @Column(name="Amount")
 private double amount;
}
Here i have abstracted out id and name from the Expense entity and moved it to a separate class name Base,
and have the Expense entity extends Base, and i have annotated the Base class with @MappedSuperclass, note, the Base class is not an entity.

A class designated as a mapped superclass has no separate table defined for it. Its mapping information
is applied to the entities that inherit from it. An entity may inherit from a superclass that provides persistent entity state and mapping information, but which is not itself an entity. Mapping information can be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations

@MappedSuperclass
public class Base 
{
 
    @Id
    @Column(name="ID")
    @GeneratedValue
    private int id;
 
    @NotBlank(message = "Name should not be empty")
    @Column(name="NAME")
    private String name;
}


@Entity
@Table(name="Expense")
public class Expense extends Base
{

    @NotBlank(message = "Amount should not be empty")
    @Column(name="Amount")
    private double amount;
}

Happy Programming ...!!!

No comments:

Post a Comment