开发者

Map a column multiple times

I have a rather odd requirement in my fluent hibernate maps. I have an table(A) which has a compound foreign key relationship with another table(B). In the mapping for table A I would like to have both the object created from tabl开发者_如何学编程e B and access to the individual attributes of A which define the key. Is there any way to do that? I seem to get index out of range exceptions if I map the column twice.

I cannot just explore B for the attributes because the row in table B may not exist. I am painfully aware that there are some significant smells in the structure with which I'm dealing. Such is the fate of those who deal with legacy systems.


It's kinda possible, by hacking around a little.

We're going to define a domain that with a fake collection that we'll use to retrieve the single related element, if found:

public class Foo
{
    public virtual BarKey BarKey { get; set; }
    public virtual Bar Bar { get { return Bars.SingleOrDefault(); } }
    protected virtual ICollection<Bar> Bars { get; set; }
}

public class Bar
{
    public virtual BarKey Id { get; set; }
}

//this class must override Equals and GetHashcode. Implementation not shown.
public class BarKey
{
    public virtual int X { get; set; }
    public virtual int Y { get; set; }
}

The BarKey component contains the properties that are part of the key.

Now, the mapping:

<class name="Foo">
  <id ...><generator .../></id>
  <component name="BarKey">
    <property name="X" />
    <property name="Y" />
  </component>
  <bag name="Bars" inverse="true">
    <key property-ref="BarKey">
      <column name="X"/>
      <column name="Y"/>
    </key>
    <one-to-many class="Bar"/>
  </bag>
</class>
<class name="Bar">
  <composite-id name="Id">
    <key-property name="X" />
    <key-property name="Y" />
  </composite-id>
</class>

The property-ref attribute there tells NH to match those columns in Bar against the BarKey property of Foo instead of its Id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜