一对多关联映射有单向和双向之分,单向表示在一边维护他们的关系,双向表示在两边都要维护关系。首先看下单向一对多关联映射。
Customer.hbm.xml映射文件
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"
assembly="NtestRelationship"
namespace="NtestRelationship.Entities"
>
<class name="Customer">
<id type="int" name="Id">
<column name="Id" />
<generator class="identity"></generator>
</id>
<property name="FirstName"/>
<property name="LastName"/>
<bag name="Orders" cascade="all" lazy="true" fetch="select">
<key column="customerId"
not-null="false"/>
<one-to-many class="Order"/>
</bag>
</class>
</hibernate-mapping>
Order.hbm.xml映射文件
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"
assembly="NtestRelationship"
namespace="NtestRelationship.Entities"
>
<class name="Order" table="Orders">
<id type="int" name="Id">
<column name="Id" />
<generator class="identity"></generator>
</id>
<property name="Value"/>
</class>
</hibernate-mapping>
OneToManyRelation.cs类
public class OneToManyRelation
{
private readonly ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
protected object CustomerId=1;
public void AddOrderToCustomer()
{
using (var session = sessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
Customer customer = session.Get<Customer>(CustomerId);
customer.Orders.Add(new Order(){Value = 3});
customer.Orders.Add(new Order() { Value = 5 });
customer.Orders.Add(new Order() { Value = 13 });
session.Save(customer);
transaction.Commit();
}
using (var session = sessionFactory.OpenSession())
{
Customer customer = session.Get<Customer>(CustomerId);
Console.WriteLine("Orders NotBeEmpty IS :" + customer.Orders.Count);
}
}
}
主程序:
class Program
{
static void Main(string[] args)
{
OneToManyRelation omr = new OneToManyRelation();
omr.AddOrderToCustomer();
Console.ReadKey();
}
}
运行结果如图:
数据结果