I’m trying to move some old code from hand-made persistence to Hibernate. The issue here is a peculiar mapping where the target entity type/table is defined by a column value.
Example database table:
Table “Relation”:
- id – my primary key
- parentType – a char that specifies the type of parent (e.g. ‘I’ meaning an object in the Item table, ‘C’ in the Category table)
- parentId – primary key in the table of parentType
- childType – a char that specified the type of child
- childId – primary key in the table of the child
The thing is that all these types (such as Item or Category) have the same abstract parent called GenericObject, which doesn’t have its own table. The inheritance is TABLE_PER_CLASS.
The bad thing is that by the parentId or childId you cannot tell the type, the id is not unique among these tables. You need to look at parentType and childType.
Now how do I map this madness in Hibernate? I would like to have the parent and child mapped to a GenericObject variable, which would actually be an instance of Item or Category.
Any ideas?
Hibernate has
@Anyand@ManyToAnyannotations for the cases when target entity is identified by type and non-unique id.I think in your case, since both parent and child are identified this way, you need to create
Relationentity with relations to parent and child annotated with@Any.