简体   繁体   中英

JPA Inheritance modelling problem

here's my problem. I have 3 classes, a parent class representing money flows. Two subclasses one for incomes and another for expenses. The thing is that I subclass to override behavior, not state. So in the database I should only have one table with a type column. I can do that using the Joined strategy, but tables for income and expenses are still created right?. Is there anyway to map this?

Basically my idea, is to have only one table representing money flows with a type attribute so the orm knows whether to instance an "Income" or "Expense". I want to do this because the difference is in behavior and not state, so the tables for Income and expense would not have any column except for the key.

I could create one class and have a type attribute but it leads to a very dirty code and I would prefer to use polimorphism. Plus my code looks so much cleaner that way.

Sounds like what you're describing is exactly just the Single Table inheritance type . Everything is stored in one table. You just specify a Discriminator Column and JPA will decide which type of object to use based on the value of that. The example in the java doc for Discriminator Column implements what you want to do.

That all sounds reasonable to me. One question is whether the data base operations differ for income and expenses. Another is whether the model is expected to evolve beyond the situation you have now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM