views:

46

answers:

2

I've got a curious puzzle with an object-relational mapping, using Java and Hibernate.

We have an existing schema that looks something like this:

create table foo (id int8, /* ... */ primary key (id));
create table bar (id int8, foo int8, /* ... */ primary key (id));
alter table bar add constraint fk_foobar foreign key (foo) references foo;

Normally, you would map this using a ManyToOne relationship.

class Foo { /* ... */ }
class Bar { private Foo foo; /* ... */ }

But one of the guys on my team wants to map this into an inheritance relationship:

class Foo { /* ... */ }
class Bar extends Foo { /* ... */ }

Is there any way to pull this off with Hibernate?

Edit: The important point is that the table bar has a foreign key column foo, which is distinct from bar's identity column.

A: 
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Foo { .. }

But do it only if it is logical to be inheritance. I.e. if it is Dog extends Animal, and NOT in case it is User extends Group

Bozho
A: 

You should only map this as an inheritance relationship, if Bar is a Foo. Otherwise, you should use composition. But, offcourse, I do not know the context, so I don't know whether mapping these classes as a sub and base class is correct.

Anyway, yes, it is possible to do this. Check the different possibilities to create an inheritance relationship in Hibernate.

For instance, you could use the Joined Subclass scenario here:

<class name="Foo" table="Foos">
   <joined-subclass="Bar" table="Bars">
   </joined-subclass>
</class>
Frederik Gheysels
The actual use case is sort of a gray area. Bar provides additional data about Foo. In that way, you can think about it as Bar is-a Foo. But there may be multiple objects providing additional data about the same Foo. That leans more toward Bar has-a Foo.The mapping you give doesn't map into the existing schema. The bar table has an id column distinct from the foo foreign key column.
dave
This is a composition for me because it is one-to-many. You can't have multiple Bars for the same Foo using inheritance. Think about Inheritance Mapping for all the "additional Info" objects.
zoidbeck