I have a section of my database here, simplified for the question:
Supplier
company_id int
location String
Warehouse
warehouse_id int
location String
Store
store_id int
location String
Shipment
shipment_id int
origin_id int
destination_id int
Objective: The system is used to record and track shipments between Suppliers and warehouses, warehouses and stores, and between stores.
So originally I planned to implement this by creating 3 tables each to store one type of shipment, but i realized i can abstract that by creating one table called shipment, since all the possible origins and destinations have the same length and type(int) of ids. I use shipment.type to identify if the origin is a supplier, warehouse or store, and vice versa with dest_type. My problem is how do I implement this in JPA entities? My current pseudocode for this goes like this:
@Entity
@Table(name = "SHIPMENT")
public class Shipment implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "SHIPMENT_ID")
private int shipmentId;
@Column(name = "ORIGIN_TYPE")
private int originType;
@Column(name = "DESTINATION_TYPE")
private int destination_id;
if(origin_type==1){
@ManyToOne
@JoinColumn(name = "ORIGIN_ID", nullable = false)
private Supplier supplier;
}
else if(origin_type==2){
@ManyToOne
@JoinColumn(name = "ORIGIN_ID", nullable = false)
private Warehouse warehouse;
}
else if(origin_type==3){
@ManyToOne
@JoinColumn(name = "ORIGIN_ID", nullable = false)
private Store store;
}
//same for destinations
}
I have no idea if this is even possible? And I have no idea what keywords to search for to do this because I'm self learning.
This case can be handled by Table per class
of Inheritance Mapping
.
The Table Per Class strategy maps each entity to its table which contains all the properties of the entity, including the ones inherited.
You need to make the Supplier
, Warehouse
and Store
classes as a subclass of Shipment
.And use @Inhertance
annotation for your Shipment
class as follows.
@Entity
@Table(name = "SHIPMENT")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Shipment implements Serializable
Here is an example of that.
Edited Anwer
Actually, your case mostly fit with Joined Table
for that, you need to change the Inheritence type as
@Inheritance(strategy = InheritanceType.JOINED)