Table-per-class Strategy Implementation Steps
Below are the steps to implement a Table-per-class Strategy in JPA.
1. Define the Entity class
We can define the entity class representing the inheritance hierarchy of the application.
For Example: Vehicle Entity
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Vehicle {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String manufacturer;
// Other properties and methods
}
Car Subclass:
@Entity
public class Car extends Vehicle {
private int numberOfDoors;
// Other properties and methods
}
Bike Subclass:
@Entity
public class Bike extends Vehicle {
private boolean hasBasket;
// Other properties and methods
}
2. Generate the Tables
We can generates the createEntityManagerFactory method along with the property of the hibernate.hdm2ddl.auto set to the update
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
// Create instances of vehicles
Car car = new Car();
car.setManufacturer("Toyota");
car.setNumberOfDoors(4);
Bike bike = new Bike();
bike.setManufacturer("Honda");
bike.setHasBasket(true);
// Persist the vehicles
em.persist(car);
em.persist(bike);
em.getTransaction().commit();
em.close();
emf.close();
}
JPA Table-per-class Strategy
The Table Per Class strategy is an inheritance mapping strategy where a separate table is generated for each subclass. Each concrete subclass has a table to store its properties and properties inherited from its superclasses. Table-Per-class strategy in JPA is one of the inheritance mapping strategies used to map inheritance hierarchies to the database table.
The Table-per-class strategy can involve creating a separate table for each class in the inheritance hierarchy. It means that all the properties of each class are stored in the corresponding table and it can include the inherited properties.
Syntax:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Subclass extends Superclass {
// Class definition
}
This annotation tells JPA to map the Subclass entity to a separate table, along with any properties inherited from its superclass (Superclass). Each subclass in the hierarchy annotated with @Entity and @Inheritance will be mapped to its own table in the database, as per the specified inheritance strategy.