Image Showing Values in Table with and Without DiscriminatorColumn defined

  • By Default Hibernate follows Single Table Inheritance
  • DiscriminatorColumn tells hibernate the name in which DiscriminatorColumn should be save or else it would be saved as DType
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="VEHICLE_TYPE",
		     discriminatorType=DiscriminatorType.STRING)

Vehicles.java

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="VEHICLE_TYPE",
		     discriminatorType=DiscriminatorType.STRING)
public class Vehicles {
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	private int VehicleId;	
	private String name;
		
	public int getVehicleId() {
		return VehicleId;
	}
	public void setVehicleId(int vehicleId) {
		VehicleId = vehicleId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}

TwoWheelers.java

@Entity
@DiscriminatorValue("Bike")
public class TwoWheelers extends Vehicles{
	private String steeringHolder;

	public String getSteeringHolder() {
		return steeringHolder;
	}

	public void setSteeringHolder(String steeringHolder) {
		this.steeringHolder = steeringHolder;
	}
}

FourWheelers.java

@Entity
@DiscriminatorValue("Car")
public class FourWheelers extends Vehicles{
	
	private String steeringWheel;

	public String getSteeringWheel() {
		return steeringWheel;
	}

	public void setSteeringWheel(String steeringWheel) {
		this.steeringWheel = steeringWheel;
	}
	
}

By Using the below annotation individual tables would be created for all the subclasses instead of placing all the values getting placed in a single class.

InheritanceType.TABLE_PER_CLASS

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

InheritanceType.JOINED

@Inheritance(strategy=InheritanceType.JOINED)

Using InheritanceType.JOINED gets more normalized table compared to InheritanceType.TABLE_PER_CLASS

Comments are closed.