クラスのマッピングを作成しようとしています:
public class Employer
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual IList<Field> Fields { get; set; }
public virtual string Location { get; set; }
public virtual string Phone { get; set; }
}
public class Field
{
public virtual int Id { get; protected set; }
public virtual string Description { get; set; }
}
私のマッピングは次のようになります。
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="lab" assembly="lab">
<class name="Employer" table="Employer">
<id name="Id">
<generator class="native"/>
</id>
<property name="Name" />
<list name="Fields" cascade="all-delete-orphan">
<key column="EmployerId" />
<index column="FieldIndex" />
<one-to-many class="Field"/>
</list>
<property name="Location" />
<property name="Phone" />
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="lab" assembly="lab">
<class name="Field" table="Field">
<id name="Id">
<generator class="native"/>
</id>
<property name="Description" />
</class>
</hibernate-mapping>
コードは次のようになります。
var session = configuration.BuildSessionFactory().OpenSession();
var transaction = session.BeginTransaction();
var emp = new Employer();
emp.Name = "Mera";
emp.Fields = new List<Field> ();
emp.Fields.Add(new Field() { Description = "C#" });
emp.Fields.Add(new Field() { Description = "C++" });
emp.Location = "Street";
emp.Phone = "02";
session.Save(emp);
transaction.Commit();
var transaction2 = session.BeginTransaction();
var emp2 = new Employer();
emp2.Name = "Mera2";
emp2.Fields = session.CreateQuery("from Field").List<Field>();
emp2.Location = "Street";
emp2.Phone = "02";
session.Save(emp2);
transaction2.Commit();
このコードは、フィールド テーブルの古いエントリを 2 番目の雇用主の新しいエントリに置き換えるだけです。したがって、Field テーブルにはまだ 2 つのレコードがあり、Employer テーブルには 2 つのレコードがあります。
ご理解のとおり、2 つのフィールドが等しい (同じ説明) 場合、2 つの雇用主の両方が同じオブジェクト参照を持つ必要があります。