2

In the book "Java Persistence with Hibernate, Second Edition", section 6.2 "Table per concrete class with unions" (p.120) it describes one way to map class inheritance.

The entities are:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BillingDetails {

    @Id
    @GeneratedValue(generator = Constants.ID_GENERATOR)
    protected Long id;

    @NotNull
    protected String owner;
    // ...
}

and

@Entity
public class CreditCard extends BillingDetails {

    @NotNull
    protected String cardNumber;

    @NotNull
    protected String expMonth;

    @NotNull
    protected String expYear;

    // ...
}

The SQL created to select from the tables is:

select
    ID, OWNER, EXPMONTH, EXPYEAR, CARDNUMBER,
    ACCOUNT, BANKNAME, SWIFT, CLAZZ_
from
    ( select
        ID, OWNER, EXPMONTH, EXPYEAR, CARDNUMBER,
        null as ACCOUNT,
        null as BANKNAME,
        null as SWIFT,
        1 as CLAZZ_
    from
        CREDITCARD
    union all
    select
        id, OWNER,
        null as EXPMONTH,
        null as EXPYEAR,
        null as CARDNUMBER,
        ACCOUNT, BANKNAME, SWIFT,
        2 as CLAZZ_
    from
        BANKACCOUNT
) as BILLINGDETAILS

So far the table schema is clear to me.

Now, I want to extend this schema. I want to add a new entity, Purchase, so that there are many Purchases for every BillingDetails.

Is it possible to implement it while keeping the basic schema of the BillingDetails hierarchy?

If it's possible, can you describe the tables of the extended schema?

I'm not necessarily interested in a way to describe the schema by Hibernate annotations/XML (in case that it cannot be mapped by Hibernate annotations/XML), but in the basic table structure and related SQL that can describe such a relationship.

rapt
  • 11,810
  • 35
  • 103
  • 145

1 Answers1

0

What you want is one-to-many relation BillingDetails 1 - * Purchase. There are tons of examples for this over the internet.

On a database level you would need a foreign key (FK), i.e., a reference from Purchase table to BillingDetails. Meaning that in Purchase you have a column "billing_details_id" which should point to the existing billing details record.

It is possible to achieve this without changing the BillingDetails but you might want to update BillingDetails to let Hibernate know that it is many-to-one to Purchase.

vladtkachuk
  • 656
  • 4
  • 13
  • But there is no actual `BillingDetails` table in this schema. It's only a temporary table defined in the `select` query. – rapt Jul 05 '22 at 11:23
  • got your point, this seems like your case: https://stackoverflow.com/questions/66923841/how-do-you-map-two-abstract-inheritancetype-table-per-class-entities-with-a-onet but not too nice, maybe this gives you some ideas to search more – vladtkachuk Jul 05 '22 at 11:33
  • I can't see how it's related to my case. What is the actual structure of the `Purchase` table that you are suggesting? – rapt Jul 05 '22 at 11:38