This week's giveaway is in the Beginning Java forum.
We're giving away four copies of Bad Programming Practices 101 (e-book) and have Karl Beecher on-line!
See this thread for details.
Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

java hibernate persisting classes that need data from super class?  RSS feed

 
Ranch Hand
Posts: 152
1
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Hypothetically, if I had a online shopping mall with different types of products like , clothes, books, etc, that would have extra data depending on what type they are.  In java, it seems like the best way to approach that would be to have a general product class and then child classes for items with more data specific to their type. 
If I were to persist that, how would you design the table structure?  I was thinking that you'd have a product table and some way to point to the extra data table and a foreign key.  But since there's multiple extra tables how could you point to the right table? Or is the overall design in question flawed?


Thanks!!!
 
Sheriff
Posts: 21370
91
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JPA already has support for this, as long as all your base classes are proper mapped super classes (@MappedSuperClass). Check out the following annotations:
  • DiscriminatorColumn
  • DiscriminatorValue
  • Inheritance

  • The most important one here is @Inheritance, because it's linked to how your data is actually stored. All inheritance types have their pros and cons. For instance:
  • JOINED allows you to make columns for your sub types properly non-nullable, but querying requires joining all sub class specific tables.
  • SINGLE_TABLE is the fastest, but any column that is not shared with all sub types must be nullable.
  • TABLE_PER_CLASS should probably only be used if the mapped super class is only used to define common properties, but your selects will always be limited to only one type.

  • @DiscriminatorColumn and @DiscriminatorValue should be used to let JPA determine what the actual type of a record is.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!