NHibernate 為 Java Hibernate 的 .NET 移植版,成熟穩定、支援多資料庫。採 XML 映射檔 (.hbm.xml) 與 POCO 實體類別,屬非侵入式 ORM 代表。
官網下載 (2.1.2.GA) 解壓後四資料夾:
Required_Bins:核心 DLL (NHibernate.dll, Iesi.Collections.dll, log4net.dll 等)Required_For_LazyLoading:延遲載入 Proxy 實現 (Castle/Spring/LinFu 三選一)Configuration_Templates:各資料庫 hibernate.cfg.xml 範本Tests:映射檔範例專案引用所有 Required_Bins + 選定 Proxy (如 Castle) 組件。
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
Data Source=zhou;Initial Catalog=AspNetStudy;User ID=sa;Password=jerry;
</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle
</property>
<mapping assembly="NHibernateDemo"/>
</session-factory>
</hibernate-configuration>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHibernateDemo" namespace="NHibernateDemo">
<class name="UserInfo">
<id name="UserId" column="UserId"><generator class="native"/></id>
<property name="UserName"/>
<property name="RealName"/>
<property name="Age"/>
<property name="Sex"/>
<property name="Mobile"/>
<property name="Phone"/>
<property name="Email"/>
</class>
</hibernate-mapping>
public class UserInfo
{
public virtual int UserId { get; set; }
public virtual string UserName { get; set; }
public virtual string RealName { get; set; }
public virtual int Age { get; set; }
public virtual bool Sex { get; set; }
public virtual string Mobile { get; set; }
public virtual string Phone { get; set; }
public virtual string Email { get; set; }
}
public class NHibernateCRUD
{
private readonly ISessionFactory sessionFactory;
public NHibernateCRUD()
{
sessionFactory = new Configuration().Configure().BuildSessionFactory();
}
private ISession GetSession() => sessionFactory.OpenSession();
public int Count()
{
using (var s = GetSession())
{
var q = s.CreateQuery("select count(c.UserId) from UserInfo c");
return (int)q.List<long>()[0]; // Count 回傳 long
}
}
public int Create(UserInfo info)
{
using (var s = GetSession())
{
int id = (int)s.Save(info);
s.Flush();
return id;
}
}
public UserInfo Read(int userId)
{
using (var s = GetSession())
return s.Get<UserInfo>(userId);
}
public void Update(UserInfo info)
{
using (var s = GetSession())
{
s.Update(info);
s.Flush();
}
}
public void Delete(int userId)
{
using (var s = GetSession())
{
var q = s.CreateQuery("delete from UserInfo where UserId=:UserId");
q.SetInt32("UserId", userId);
q.ExecuteUpdate();
}
}
public void Delete(UserInfo info)
{
using (var s = GetSession())
{
s.Delete(info);
s.Flush();
}
}
public int GetMaxUserId()
{
using (var s = GetSession())
return s.CreateQuery("select max(UserId) from UserInfo").List<int>()[0];
}
}
NHibernate 適合中型專案、異構資料庫環境、重視維護性與開發速度的團隊。