• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

java hibernate persisting classes that need data from super class?

 
Bartender
Posts: 667
14
TypeScript Fedora
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 22781
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
     
    Consider Paul's rocket mass heater.
    reply
      Bookmark Topic Watch Topic
    • New Topic