views:

137

answers:

4

Please excuse my ignorance on the topic, as I am relatively new to Hibernate / NHibernate, but I have encountered a mapping I can't figure out:

This is what my database table looks like:

<bincontents> 
  <id>5873715</id> 
  <title>Video Title</title> 
  <sortorder>0</sortorder> 
  <itemid>23079</itemid> 
  <itemtype>VIDEO</itemtype> 
</bincontents> 
<bincontents> 
  <id>5873716</id> 
  <title>Clip Title</title> 
  <sortorder>1</sortorder> 
  <itemid>131854</itemid> 
  <itemtype>CLIP</itemtype> 
</bincontents>

Is there a way to map a one-to-one with a where clause?

So a BinContent object can have ItemType of either VIDEO or CLIP. These are keyed as strings, and I can't change that unfortunately.

So if the ItemType field says "VIDEO", I'd like to have a Many-To-One "Video" object, However if the ItemType field says "CLIP", I'd like to have a Many-To-One Clip.

Help!

I'm not even sure if I want to use a Many-To-One in this case. Perhaps a One-To-One?

A: 

Couldn't you have both Video and Clip objects in your class and just make sure that both are never populated at the same time? Might need some more information from you such as your current class structure. Also, Is there only going to be one Video per Bin object and vice versa?

Ryan Lanciaux
+4  A: 

It sounds to me like you have a candidate for inheritance. If you have an abstract base type of BinContents, have a derived class of VideoBinContents, which contains just a Video mapping, and and a ClipBinContents which contains just a Clip mapping. Your itemtype is your discriminator. Have a look here for more: http://www.hibernate.org/hib_docs/reference/en/html/inheritance.html

James L
A: 

Perhaps this is more complicated than what you are looking for, but it seems that perhaps you could setup a base class for your bins and have sub classes of Video or Clip. Using the table per class hierarchy of inheritance, you could use your existing table structure.

Doing this would allow you to provide different mappings for each sub class.

Jim Petkus
A: 

You could take a look at the any mapping. With the 'any' mapping, you can define a polymorphic association.

Check this (paragraph 5.2.4)

Anyway , I 'm not familiar with your 'domain', but I think Jim has a point as well. Perhaps you should review your datamodel and domainmodel (if possible), and see if some kind of inheritance isn't appropriate here.

Frederik Gheysels