views:

27

answers:

1

I have a class Player that contains a list of Accessory objects. There are two kinds of Accessories. SocketedAccessories have a list of SocketJewels, and MagicAccessories have a list of MagicEnchantments.

At the database level, there is a players table that represents the player, and an accessories table that contains a list of accessories. Accessories have a type field that indicates whether they are socketed or magical, and the columns that are only used by one type are just left blank by entries of the other type. There are socket_jewels and magic_enchantments tables, representing the socket jewels or the magic enchantments on each accessory.

I am trying to figure out the correct way to map this with Hibernate. One way would be for the player to have two lists of accessories, one for SocketedAccessories and one for MagicAccessories. That seems undesirable, though. What I want is a way to specify that player should have a field List<Accessory> accessories that contains both types of thing.

Is there a way to tell Hibernate, in either hbm.xml or annotations, to do this?

+2  A: 

Is there a way to tell Hibernate, in either hbm.xml or annotations, to do this?

What you're describing looks like a Single Table per Class Hierarchy Strategy (all properties of all super- and subclasses are mapped into the same table, instances are distinguished by a special discriminator column).

You can map this with annotations and/or xml mappings (and have a single List, Hibernate supports polymorphic queries i.e. you can query on the Accessory superclass and get a list of subclasses).

Update: If Accessory is an interface, have a look at this previous answer.

Pascal Thivent
This is good news! Although, it looks like "Accessory" must be a base class and not an interface if I want to have a List of them?
CaptainAwesomePants
@CaptainAwesomePants Accessory can be an interface. But you might have to use hbm then. The hibernate core documentation actually explicitly mentions that you can use interfaces. I'll add a link to another answer covering the case of interfaces with JPA.
Pascal Thivent
Ah, I see, I missed the fact that Payment was an interface (and also missed the "annotating interfaces is currently not supported" bit). Thank you!
CaptainAwesomePants