5

次の説明を持つクラスがあります。

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

Contacts プロパティを次のテーブルにマップしたい:

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

双方向にマップする必要があります。つまり、Customer1 が Customer2 の Contacts に追加された場合、Customer1 の Contacts コレクションには Customer2 が含まれている必要があります (エンティティのリロード後のみ)。どうすればそれができますか?

更新確かに、左から右および右から左のセットをマップして、実行時に結合できますが、それは...うーん...おいしくない...他の解決策はありますか? とにかく、 FryHardさん、ありがとうございました!

4

1 に答える 1

2

hibernate が一方向多対多関連と呼ぶものについては、このリンクを参照してください。Castle ActiveRecordでは、HasAndBelongsToMany リンクを使用していますが、nhibernate で正確にどのようにマッピングされているかはわかりません。

あなたの質問をもう少し詳しく見てみると、顧客から user_contacts に双方向でリンクしているように見えますが、これは多対多のリンクを壊す可能性があります。例で遊んで、何が思いつくか見てみましょう。

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; }
}

それが役に立てば幸い!

于 2008-10-09T07:21:19.947 に答える