Introduction
Inheritance in EJB can be implemented from a mapped superclass or from an entity superclass. In both cases the superclass can be declared abstract. You would use an entity superclass if
Otherwise, inheritance through a MappedSuperclass is equivallent to entity inheritance using one table per class strategy. However, if you use a MappedSupperclass you will not be able to refer to this class in EJB QL (query language).
Inheritance through the @MappedSuperclass annotation
Using the @MappedSuperclass annotation will map subclasses to separate tables– similar to a TABLE_PER_CLASS strategy mentioned below.
@MappedSuperclass
public abstract class Shipment{
....
}
@Entity
@Table(name="airShipment") // optional
public class AirShipment extends Shipment {
....
}
@Entity
@Table(name="oceanShipment") // optional
public class OceanShipment extends Shipment {
....
}
Entity Inheritance
Entity inheritance is done through the @Inheritance annotation on the superclass entity and will require one of the following strategies:
The JOINED strategy will require a table for the superclass entity. The tables for the subclass entities will have foreign keys that reference the primary key in the superclass entity table. This superclass entity table will also have a discriminator field which the EJB container will use to determine how to instantiate a concrete entity. JBoss implements this discriminator table automatically, but here’s how you would implement to insure portability:
@Entity
@Table(name="shipment") // optional
@Inheritance(strategy=InheritanceType.JOINED) // REQUIRED
@DiscriminatorColumn(name="shipment_type", discriminatorType=DiscriminatorType.INTEGER) // optional in JBoss
public abstract class Shipment{
....
}
@Entity
@Table(name="airShipment") // optional
@DiscriminatorValue("1"); // optional in JBoss
public class AirShipment extends Shipment {
....
}
@Entity
@Table(name="oceanShipment") // optional
@DiscriminatorValue("2"); // optional in JBoss
public class OceanShipment extends Shipment {
....
}