NHibernate学习手记(4) - 持久化类(Persistent class)的设计

NH中把需要持久化服务(保存到数据库)的类称为Persistent class,目的和常见的Serializable(可序列化)一样,都是把程序运行时创建的临时对象(transient objects)保存到数据库、文件等介质中。

 

NH的Online Document推荐的持久化类设计模式称为POCO(Plain Old CLR Object Model)和我们的BusinessEnitity层的设计基本一致。

下面是一个简单订单(Order)的类定义

using System;

namespace NHConsole
{
///
/// Order 的摘要说明
///   
/// 创 建 人: Aero
/// 创建日期: 2006-3-16
/// 修 改 人:
/// 修改日期:
/// 修改内容:
/// 版 本:
public class Order
{
private Guid _orderId;
private DateTime _placeTime = System.DateTime.Now;
private Customer _customer = null;
private string _shipToPlace = string.Empty;
private System.Collections.IList _items = null;

public Guid OrderID
{
get { return this._orderId; }
set { this._orderId = value; }
}

public Customer Customer
{
get { return this._customer; }
set { this._customer = value; }
}

public DateTime PlaceTime
{
get { return this._placeTime; }
set { this._placeTime = value; }
}

public string ShipToPlace
{
get { return this._shipToPlace; }
set { this._shipToPlace = value; }
}

public System.Collections.IList Items
{
get { return this._items; }
set { this._items = value; }
}


#region 构造函数
///
/// 默认无参构造函数
///
/// 创 建 人: Aero
/// 创建日期: 2006-3-16
/// 修 改 人:
/// 修改日期:
/// 修改内容:
public Order()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

#endregion
}
}

可总结出POCO风格的几种特点

1、不考虑实体类的操作(通常会有相应的业务层去处理,一般称为EntityManager或EntityService),只定义了实体的数据成员和对应的getter/setter。

2、带无参构造函数(default constructor)。

NH通过反射和动态代理的机制来实现O/R映射,所以上述的getter/setter和constructor可定义为public/protected/private,甚至是internal。

Martin Fowler称这样的设计模型为贫血模型(http://forum.javaeye.com/viewtopic.php?t=11712),我也认为把对象的操作和对象的数据剥离是一种非常丑陋的设计,随着NH学习的深入,以后的文章也想讨论一些关于领域模型和设计模式的话题。

posted @ 2006-03-17 09:12  海南K.K  阅读(3421)  评论(8编辑  收藏  举报