By Peter Bell

Inheritance in Hibernate: Should an Object Ever Have More than one Type?

Let's say you have an inheritance hierarchy where Vendor and Customer are both subclasses of Company. So, you deal with companies that could be Vendors or Customers. The question is, what happens if a given Company is both a Vendor and a Customer? . . .

In Hibernate, if you use single table inheritance (table per class hierarchy), there is an automatically populated discriminator field - say COMPANY_TYPE, which Hibernate will populate with the appropriate type. But this assumes that any given object can only have one type (as you can only put a single value in the discriminator field).

One solution would be to say that a company has-many Roles where you could have a vendor and a customer role that a company could assume. However, this is adding a fair bit of complexity to the model. I'm not even sure immediately how you'd model this in Hibernate. I guess you could say Company has-many Roles and then use subclassing to provide a VendorRole and a CustomerRole - each with their own tables.

So, as a general question, can an object in an OO system ever have more than one type. If not, why not. And if not, how would you solve something like the above scenario fairly simply?

Input much appreciated!

Comments
This really has nothing to do with Hibernate - it's a simple OO modeling question. The simple solution is to use interfaces: create Vendor and Customer interfaces that extend the Company interface. You'll need VendorImpl and CustomerImpl classes, along with a VendorCustomerImpl class, and maybe a CompanyImpl class if Company isn't abstract. However, as you allude to, inheritance isn't really the right solution.

The role solution is a better one: create Company and Role interfaces and CompanyImpl, VendorRole, and CustomerRole classes, and compose them together. This second option is more complex, no question, but it's far more flexible (what happens when you add Supplier to the mix? And then Reseller?).

Once you pick the right way to model you app, Hibernate will happily persist either one with little fuss. If you find yourself structuring your domain model based on the limitations of your persistence framework, something's wrong.

I had a HUGE problem with this issue when I first started using Hibernate; I spent my time figuring out how I wanted to map stuff to the DB and what the implications of different decisions would be, and then figured out how to structure my domain model from there. Now I just create my entities, annotate them as simply as possible, and let Hibernate figure out how to put them in the DB. If there ends up being an issue later, I'll redo the mappings, but I rarely do. In any case, the mappings is where that should happen, not in the domain mode.
# Posted By Barney | 7/14/08 2:47 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.005.