Bal
Bal

Reputation: 2087

Hibernate ORM design strategy

I need to build a Vehicle domain object. All Vehicle objects will have about 5 properties... no big deal. I annotate the class with @Entity, slap in an id annotated with @Id. My problem is, there are two other types of specialty vehicles I need to account for. One needs to hold 2 additional string values, and the other needs to hold a list of strings.

I would like to be able to do a findAll() and get all of the vehicles, so I'm not really sold on creating completely separate domain objects for the other two types of vehicles and having completely separate tables for them. I toyed around with an idea to create an "AdditionalProperties" abstract class, make it a member of Vehicle, then extend it for my two specialty vehicles, but I quickly got lost in the proper way to annotate it and map it to the database. But even then I'd be stuck with writing lots of monolithic if statements to check vechicle type and cast that class etc etc

My other thought was just to include the extra fields in the single Vehicle domain object I have now (even though they don't make any sense for all the other types of vehicles) and leave the values null except for when it is one of the specialty vehicles.

Does anybody have any ideas on how I should approach this with possibly some examples of how the classes should be annotated?

Upvotes: 0

Views: 275

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

Why don't you simply create two subclasses of Vehicle, and containing the additional properties? Hibernate supports inheritance just fine. You'll have three options to persist the entity inheritance tree:

  • everything in a single table (often the fastest and simplest option)
  • every entity in its own table
  • common properties in a common table, and additional sub-entity properties in their own table.

Whatever solution you choose, selecting vehicles will select all the kinds of vehicles satisfying the criteria. Hibernate queries are polymorphic.

Read the documentation.

Upvotes: 3

Related Questions