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; }
}
构造函数
}
{
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; }
}
构造函数
}
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);
}
}
{
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;
}
}
{
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;
}
}
}
{
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; }
}
构造函数
}
{
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; }
}
构造函数
}
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 );
}
}
{
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();
}
}
}
{
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();
}
}
{
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 操作.
}
}
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 操作.
}
}
可以看到这种实现方式,实体类既有业务数据,也有业务操作。哪种实现方式更好一些呢?
支持TerryLee的创业产品Worktile
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com