views:

38

answers:

1

Hi,

I have 2 existing tables in my database. Let's call them Table and Chair for now. Both these tables are mapped as entities in Hibernate

Both these tables have existed in my database for some time now, and they have their own, auto generated, ID's as primary keys.

Now however, I want to group those entities under the very logical Furniture interface in my Java code so I can have a List in my House class.

I've looked into Hibernate inheritance but don't seem to figure it out. How can I let my House class get a list of all the Furniture it owns? And which inheritance mapping strategy should I use?

Thanks, Bart

+1  A: 

You are on the right track. If you create Furniture interface, or base class, and have Table and Chair implement/extend that type, you should be good to go. You can then have a

List<Furniture> 

for your House.

The only case where you would need to modify your mapping is if you want to implement any of the polymorphic mapping strategies outlined in the hibernate documentation. Some options are

  1. to create a Furniture table and have all Chairs/Tables in that table instead (One table per class hierarchy). You do not have to do this. In this case your table would have all the properties of both classes, so not all columns would be used depending on the type being persisted. There would be a 'discriminator' column so hibernate could tell the type of a row.

  2. You want to create a Furniture table, and refactor/normalize your Table/Chair tables so that all common fields are pulled into the Furniture table. You keep the Table and Chair tables. This is another type of polymorphic mapping (check the docs)

  3. Other options in the hibernate docs.

Option 1 is the preferred strategy in the hibernate docs, I believe.

But to get down to it, you don't have to do any of these -- your entities can extend/inherit from other types without any special mapping considerations, if you are willing to have the duplicate columns in the tables.

I would write some simple JUnit or whatever tests and try it out.

hvgotcodes