刚才看到Aero老兄写的《NHibernate学习手记(4) - 持久化类(Persistent class)的设计》的文章,谈到了NHibernate下持久化类的设计时关于关于对象的操作和数据是否应该剥离的问题,想到了我经常看到的两种不同的设计,虽然现在已经没时间再去研究NHibernate了,但还是把这两种实现方法贴出来,大家可以讨论一下。
刚才看到Aero老兄写的《NHibernate学习手记(4) - 持久化类(Persistent class)的设计》的文章,谈到了NHibernate下持久化类的设计时关于关于对象的操作和数据是否应该剥离的问题,想到了我经常看到的两种不同的设计,虽然现在已经没时间再去研究NHibernate了,但还是把这两种实现方法贴出来,大家可以讨论一下。
一.剥离对象的操作和数据
1.实体类
public class User


{
private string id;

private string userName;

private string password;

private string emailAddress;

private DateTime lastLogon;

public string Id

{

get
{ return id; }

set
{ id = value; }
}

public string UserName

{

get
{ return userName; }

set
{ userName = value; }
}

public string Password

{

get
{ return password; }

set
{ password = value; }
}

public string EmailAddress

{

get
{ return emailAddress; }

set
{ emailAddress = value; }
}

public DateTime LastLogon

{

get
{ return lastLogon; }

set
{ lastLogon = value; }
}


构造函数#region 构造函数


/**//// <summary>
/// 无参构造函数
/// </summary>
public User()

{
//
// TODO: 在此处添加构造函数逻辑
//
}
#endregion
}
2.对象操作
public class UserDAL


{
private EntityControl control;

public UserDAL()

{
control = EntityControl.CreateEntityControl("NHibernateWebDemo.Model");
}
//新增
public void AddUser(User user)

{
control.AddEntity(user);
}
//修改
public void UpdateUser(User user,string Id)

{
control.UpdateEntity(user,user.Id);
}
//删除
public void DeleteUser(User user)

{
control.DeleteEntity(user);
}
}
3.公用的类
public class EntityControl


{
private static EntityControl entity;
private string _AssemblyName;
static readonly object padlock = new object();

public static EntityControl CreateEntityControl(string AssemblyName)

{
if(entity == null)

{
lock(padlock)

{
if(entity == null)

{
entity = new EntityControl();
entity._AssemblyName = AssemblyName;
}
}
}
return entity;
}

public void AddEntity(Object entity)

{
ISession session = SessionFactory.OpenSession(_AssemblyName);
ITransaction transaction = session.BeginTransaction();
try

{
session.Save(entity);
transaction.Commit();
}
catch(Exception ex)

{
transaction.Rollback();
throw ex;
}
finally

{
session.Close();
}
}
public void UpdateEntity(Object entity,Object key)

{
ISession session = SessionFactory.OpenSession(_AssemblyName);
ITransaction transaction = session.BeginTransaction();
try

{
session.Update(entity,key);
transaction.Commit();
}
catch(Exception ex)

{
transaction.Rollback();
throw ex;
}
finally

{
session.Close();
}
}
public void DeleteEntity(object entity)

{
ISession session = SessionFactory.OpenSession(_AssemblyName);
ITransaction transaction = session.BeginTransaction();
try

{
session.Delete(entity);
transaction.Commit();
}
catch(Exception ex)

{
transaction.Rollback();
throw ex;
}
finally

{
session.Close();
}
}

public IList GetEntities(string strHQL)

{
IList lst;
ISession session = SessionFactory.OpenSession(_AssemblyName);
ITransaction transaction = session.BeginTransaction();

lst=session.Find(strHQL);
transaction.Commit();
session.Close();
return lst;
}
}
public class SessionFactory


{
public SessionFactory()

{
}

private static ISessionFactory sessions;
private static Configuration cfg;
static readonly object padlock = new object();
public static ISession OpenSession(string AssemblyName)

{
if(sessions == null)

{
lock(padlock)

{
if(sessions == null)

{
BuildSessionFactory(AssemblyName);
}
}
}
return sessions.OpenSession();
}

private static void BuildSessionFactory(string AssemblyName)

{
try

{
cfg = new Configuration();

cfg.AddAssembly(AssemblyName);

sessions = cfg.BuildSessionFactory();
}
catch(Exception ex)

{
throw ex;
}
}
}
这种方式的实现,在前面我曾经写过的一个例子中出现过,持久化类跟我们在开发三层结构系统中的业务实体是一样的。
二.对象的操作和数据在一起
1.实体类
public class Customer : BizObject


{
private string _customerId = string.Empty;

private string _companyName = string.Empty;

private string _contactName = string.Empty;

private string _contactTitle = string.Empty;

private string _address = string.Empty;

private string _city = string.Empty;

private string _region = string.Empty;

private string _postalCode = string.Empty;

private string _country = string.Empty;

private string _phone = string.Empty;

private string _fax = string.Empty;

public string CustomerId

{

get
{ return _customerId; }

set
{ _customerId = value; }
}
public string CompanyName

{

get
{ return _companyName; }

set
{ _companyName = value; }
}
public string ContactName

{

get
{ return _contactName; }

set
{ _contactName = value; }
}
public string ContactTitle

{

get
{ return _contactTitle; }

set
{ _contactTitle = value; }
}
public string Address

{

get
{ return _address; }

set
{ _address = value; }
}
public string City

{

get
{ return _city; }

set
{ _city = value; }
}
public string Region

{

get
{ return _region; }

set
{ _region = value; }
}
public string PostalCode

{

get
{ return _postalCode; }

set
{ _postalCode = value; }
}
public string Country

{

get
{ return _country; }

set
{ _country = value; }
}
public string Phone

{

get
{ return _phone; }

set
{ _phone = value; }
}
public string Fax

{

get
{ return _fax; }

set
{ _fax = value; }
}

构造函数#region 构造函数

/**//// <summary>
/// 无参构造函数
/// </summary>
public Customer()

{
//
// TODO: 在此处添加构造函数逻辑
//
}

/**//// <summary>
/// 带参构造函数
/// </summary>
/// <param name="existingId"></param>
public Customer( string existingId ) : base( existingId )

{
}
#endregion
}
BizObject类的实现如下:
public class BizObject


{

public BizObject()
{ }

public BizObject( object existingId )

{
ObjectBroker.Load( this, existingId );
}
public virtual void Create()

{
ObjectBroker.Create( this );
}
public virtual void Update()

{
ObjectBroker.Update( this );
}
public virtual void Delete()

{
ObjectBroker.Delete( this );
}
}
2.公用类
public class ObjectBroker


{

private ObjectBroker()
{ }

public static void Load( object obj, object id )

{
ISession s = Sessions.GetSession();
try

{
s.Load( obj, id );
}
finally

{
s.Close();
}
}

public static void Create( object obj )

{
ISession s = Sessions.GetSession();
ITransaction trans = null;
try

{
trans = s.BeginTransaction();
s.Save( obj );
trans.Commit();
}
finally

{
s.Close();
}
}

public static void Update( object obj )

{
ISession s = Sessions.GetSession();
ITransaction trans = null;
try

{
trans = s.BeginTransaction();
s.Update( obj );
trans.Commit();
}
finally

{
s.Close();
}
}

public static void Delete( object obj )

{
ISession s = Sessions.GetSession();
ITransaction trans = null;
try

{
trans = s.BeginTransaction();
s.Delete( obj );
trans.Commit();
}
finally

{
s.Close();
}
}
}
public class Sessions


{
private static readonly object lockObj = new object();
private static ISessionFactory _factory;

public Sessions()

{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static ISessionFactory Factory

{
get

{
if ( _factory == null )

{
lock ( lockObj )

{
if ( _factory == null )

{
Configuration cfg = new Configuration();
cfg.AddAssembly( Assembly.GetExecutingAssembly() );
_factory = cfg.BuildSessionFactory();
}
}
}
return _factory;
}
}
public static ISession GetSession()

{
return Factory.OpenSession();
}

}
3.测试操作
[TestFixture]
public class CustomerFixture


{
public CustomerFixture()

{}

[Test] // 测试Customer对象的CRUD操作。
public void TestCRUD()

{
Customer c = new Customer();
c.CustomerId = "test";
c.CompanyName = "company name";
c.ContactName = "contact name";
c.Address = "address";
c.Create(); // 测试 insert操作,

Customer c2 = new Customer( c.CustomerId ); // 测试 retrieve 操作.
Assert.AreEqual( c2.CompanyName, "company name", "save companyname fail! " );

c2.CompanyName = "update name";
c2.Update(); // 测试 update 操作.

Customer c3 = new Customer( c.CustomerId );
Assert.AreEqual( c3.CompanyName, "update name", "update companyname fail! " );

c3.Delete(); // 测试 delete 操作.
}
}
可以看到这种实现方式,实体类既有业务数据,也有业务操作。哪种实现方式更好一些呢?
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)