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.
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: