Single table per class hierarchy
This approach may be considered the most simple: We just create one database table for storing instances of arbitrary classes belonging to the inheritance hierarchy in question:
Todo: Ref/Fig/billingData.fig
Fitting both inherit.v1.CreditCard
and inherit.v1.BankAccount
instances into
a single relation.
The relation may be created by the following DDL:
Todo: Ref/Fig/billingSql.fig
We take a closer look at the generated relation. Since
Java |
|
Sql |
|
All classes of the inheritance hierarchy will be mapped to a
single table. Unless stated otherwise the JPA provider will choose the root class' name
( |
|
The JPA provider needs a column to
distinguish the different types of database objects. We've chosen
the discriminator attribute
In a productive system the
|
|
This one is unrelated to inheritance: Our primary key values
will be auto generated by the database server e.g. by
|
|
Only the base class' attributes may exclude
|
|
All derived classes' attributes must allow |
We may now insert instances of
inherit.v1.BankAccount
or
inherit.v1.CreditCard
:
package inherit.v1;
...
public class Persist {
public static void main(String[] args) throws ParseException {
... final Transaction transaction = session.beginTransaction();
{
final CreditCard creditCard = new CreditCard("4412 8334 4512 9416", 1, "05/18/15");
session.save(creditCard);
final BankAccount bankAccount = new BankAccount("1107 2 31", "Lehman Brothers", "BARCGB22");
session.save(bankAccount);
}
transaction.commit(); ...