代码之家  ›  专栏  ›  技术社区  ›  Brandon

双向多对多关联

  •  5
  • Brandon  · 技术社区  · 16 年前

    我有一门课,描述如下:

    public class Customer {
        public ISet<Client> Contacts { get; protected set;}
    }
    

    我要将“联系人”属性映射到下表:

    CREATE TABLE user_contacts (
        user1 uuid NOT NULL,
        user2 uuid NOT NULL
    )
    

    我希望它双向映射,即当customer1添加到customer2的contacts时,customer1的contacts集合应该包含customer2(可能只有在实体重新加载之后)。我怎么能做到?

    更新 当然,我可以从左到右和从右到左映射集,然后在运行时合并,但它会…隐马尔可夫模型。。。不好吃…还有其他解决办法吗?无论如何,谢谢你的配合, 弗里哈德 !

    1 回复  |  直到 15 年前
        1
  •  2
  •   FryHard    16 年前

    看看这个链接,了解Hibernate称之为单向的 many-to-many associations . 在 Castle ActiveRecord 我使用了hasandbelongmotorny链接,但我不确定它在nhibernate中的映射方式。

    虽然稍微深入了解一下您的问题,但看起来您将双向链接客户与用户的联系人,这可能会破坏许多链接。我会举个例子,看看我能想出什么。

    从ActiveRecord导出HBM文件显示

    <?xml version="1.0" encoding="utf-16"?>
    <hibernate-mapping  auto-import="true" default-lazy="false" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:nhibernate-mapping-2.2">
      <class name="NHibernateMapping.Customer, NHibernateMapping" table="Customer" schema="dbo">
        <id name="Id" access="property" column="Id" type="Int32" unsaved-value="0">
          <generator class="identity">
          </generator>
        </id>
        <property name="LastName" access="property" type="String">
          <column name="LastName" not-null="true"/>
        </property>
        <bag name="ChildContacts" access="property" table="user_contacts" lazy="false">
          <key column="user1" />
          <many-to-many class="NHibernateMapping.Customer, NHibernateMapping" column="user2"/>
        </bag>
        <bag name="ParentContacts" access="property" table="user_contacts" lazy="false" inverse="true">
          <key column="user2" />
          <many-to-many class="NHibernateMapping.Customer, NHibernateMapping" column="user1"/>
        </bag>
      </class>
    </hibernate-mapping>
    

    活动记录示例:

    [ActiveRecord("Customer", Schema = "dbo")]
    public class Customer
    {
        [PrimaryKey(PrimaryKeyType.Identity, "Id", ColumnType = "Int32")]
        public virtual int Id { get; set; }
    
        [Property("LastName", ColumnType = "String", NotNull = true)]
        public virtual string LastName { get; set; }
    
        [HasAndBelongsToMany(typeof(Customer), Table = "user_contacts", ColumnKey = "user1", ColumnRef = "user2")]
        public IList<Customer> ChildContacts { get; set; }
    
        [HasAndBelongsToMany(typeof(Customer), Table = "user_contacts", ColumnKey = "user2", ColumnRef = "user1", Inverse = true)]
        public IList<Customer> ParentContacts { get; set; }
    }
    

    希望它有帮助!