Search code examples
hibernateannotationsone-to-onediscriminator

One-to-one relationship between one type and sub-classes of another type using Hibernate


Using Hibernate, I am trying to implement a one-to-one relationship between one fixed domain type A and another domain type B whose type be any type which implements a certain interface.

Situation:

The system has three distinct domain types; Country, Warehouse and Store, which implement an interface FlagSubscriber.

I would like to join FlagSubscribers with Flags. Each Flag can be paired with 0 or 1 FlagSubscribers.

Implementation:

In the database I have tables for Country, Warehouse, Store and Flag which each have an ID column and various other columns for their specific attributes. In order to pair Flags with FlagSubscribers I have created a link table which looks like this:

  • flag_id
  • subscriber_id
  • subscriber_type

The id fields are self-explanatory, the subscriber_type is a text field which determines whether the subscriber_id relates to a Country, Warehouse or Store.

Question:

Using Hibernate annotations, how do I tell Hibernate how to map FlagSubscribers in the Flag class?

I presume I need to use discriminators, but I am not exactly sure how to do this for my specific case, or even if it is possible.

Any pointers to examples, suggestions or ideas would be most welcome!


Solution

  • Perhaps it can be mapped using @Any annotation, though I'm not sure how would it play with a link table. However, since relationship between Flag and FlagSubscriber is one-to-one, you can map it without link table.

    Also note that it wouldn't work since Hibernate 3.5 if Hibernate is used via EntityManager interface.