This week's book giveaway is in the Web Services forum.
We're giving away four copies of Microservices in Action and have Morgan Bruce & Paulo A. Pereira on-line!
See this thread for details.
Win a copy of Microservices in Action this week in the Web Services forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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

Ranch Hand
Posts: 207
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?

Posts: 21466
Chrome Eclipse IDE Java Spring Ubuntu VI Editor 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.
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!