JPA: how can I extend classes and change the table

2019-09-16 10:27发布

问题:

I have created a basic set of classes with methods for doing accounting.

My Ledger class allows you to maintain a basic ledger which allows you to obtain the current balance, and to perform transactions on the ledger that adds a new LedgeEntry.

I have this generic ledger system working well.

Insider Ledger is my LedgerEntry collection which is a List entries.

Now, I want to use this to create Billing / BillingEntry entities (which map to say BILLING and BILLING_ENTRIES table) and CustomerCredits / CustomerCreditsEntry entites (mapped to CUST_CREDITS; CUST_CREDITS_ENTRY).

I would like to create these classes by extending from Ledger and LedgerEntry. The parent entity class (Ledger, Billing, CustomerCredits) can be easily mapped to a different table using the @Table annotation.

But I'm not sure how to handle the replacing the LedgerEntry entities with their corresponding BillingEntry, CustomerCreditsEntry.


Edit 2010-09-24:

I just gave up and am having all Ledger-derviced entites go to child LedgerEntry entities (for now).

The problem here, I think, is that I can't make methods in a parent class that refer to objects that would only exist in the inherited class?

回答1:

It sounds like the purrrfect scenario for generics :)

I imagine something like:

public class Ledger<T extends LedgerEntry> {
   List<T> entries;
   // getters and setters
}

public class CustomerCreditsLedger extends Ledger<CustomerCreditsEntry> {
}

And probably for wiring up JPA with the table inheritance take a look at: http://www.jpox.org/docs/1_2/jpa_orm/inheritance.html (it is old, but seems to be correct and figuring the annotation-based config out is not that hard). From what I read you should be looking at JOINED or TABLE_PER_CLASS strategies.



标签: java jpa mapping