Tables are generated as persistent classes in the table per subclass technique, but they are processed using primary and foreign keys, as we said before. As a result, there will be no duplicate columns in the relationship.
The parent class must have @Inheritance(strategy=InheritanceType.JOINED) and the subclasses must have @PrimaryKeyJoinColumn annotation.
The base class is Vehicle, and the subclasses are Bus and Car. In the Bus and Car tables, the vehicle id will be used as a foreign key, and common data (vehicleId) will be kept in the VEHICLE table, while subclass specific attributes will be stored in the BUS and CAR tables.
To save classes, create a database table.
PRIMARY KEY (vehicle id) ; CREATE TABLE VEHICLE ( vehicle id int NOT NULL AUTO INCREMENT, vehicle name VARCHAR(50), type VARCHAR(50), PRIMARY KEY (vehicle id) );
CREATE TABLE CAR ( vehicle id int NOT NULL, car model VARCHAR(50), PRIMARY KEY (vehicle id), CONSTRAINT FK CAR FOREIGN KEY (vehicle id) REFERENCES VEHICLE (vehicle id) REFERENCES VEHICLE (vehicle id) );
CREATE TABLE BUS ( vehicle id int NOT NULL, bus model VARCHAR(50), PRIMARY KEY (vehicle id), CONSTRAINT FK BUS FOREIGN KEY (vehicle id) REFERENCES VEHICLE (vehicle id) REFERENCES VEHICLE (vehicle id) );
Consider the interface IPayment, which has the implementors CreditCardPayment, CashPayment, and ChequePayment. The table-per-hierarchy mapping might look something like this:
id name="Id" type="Int64" column="PAYMENT ID"> generator class="native"/> /id> discriminator column="PAYMENT TYPE" type="String"/> /id> discriminator column="PAYMENT TYPE" type="String"/> /id> discriminator column="PAYMENT TYPE" type="String"/> /id
... subclass name="CreditCardPayment" discriminator-value="CREDIT"> property name="CreditCardType" column="CCTYPE"/>... subclass name="CreditCardPayment"
discriminator-value="CREDIT">
.../subclass> /subclass name="CashPayment" discriminator-value="CASH"> /subclass name="CashPayment" discriminator-value="CASH"> /subclass name="CashPayment"
discriminator-
.../subclass> subclass name="ChequePayment" discriminator-value="CHEQUE"> subclass name="ChequePayment" discriminator-value="CHEQUE">
.../subclass>.../class>.../subclass>
.../class>.../class>.../class>.../class>.../
There is just room for one table. This mapping technique has one drawback: columns specified by subclasses, like CCTYPE, cannot have NOT NULL constraints.