NHibernate3快速上手教程FluentNHibernate配置與DBHelper(已過期,有更好的)


很多學習NHibernate的新手很容易卡在配置文件這一關,正所謂萬事開頭難,上手后再配合官方文檔就比較容易了。

網上關於配置文件的資料非常多,但由於版本的問題,許多老的教程中都沒有明確指出類庫的版本號,

另外許多人抱怨配置比較麻煩,本教程結合FluentNHibernate簡化配置,快速上手。

 

下載類庫、版本要求:

NHibernate 3 及以上

Iesi.Collections 1.0.1.0

FluentNHibernate 1.4.0.0

.NET Framework 3及以上

NH3已經將日志與動態代理的類庫集成了,所以只需要引入前兩個配置文件。

 

總體思路:

1、通過配置文件hibernate.cfg.xml配置數據庫連接;

2、配置文件注入到FluentNHibernate;

3、並添加實體模型的映射程序集到FluentNHibernate;

 

hibernate.cfg.xml:

數據庫Oracle10g配置文件,看到那段被注釋的英文了嗎?

大致意思就是其他數據庫可以參考NH包里面的數據庫名稱對應的配置文件,然后把文件名改成hibernate.cfg.xml,放在類庫的根目錄。

別忘了將配置文件復制到輸出目錄

 

<?xml version="1.0" encoding="utf-8"?>
<!-- 
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it 
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.OracleClient.dll provider for Oracle from MS -->
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="MyManager">
        <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
        <property name="connection.connection_string">
      User ID=user;Password=pwd;Data Source=oracle
    </property>
        <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
        <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
    </session-factory>
  
</hibernate-configuration>


順手建立一個DBHelper類,或者叫SessionBuilder,直接復制一步到位。

    /*
* by:13yan
*/
public class SessionBuilder { private static ISessionFactory sessionFactory = null; private static object _lock = new object(); #region 初始化 生成SessionFactory,並配置上下文策略 public static void Instance(string currentSessionContextClass) { lock (_lock) { Configuration cfg = new Configuration() .Configure() .SetProperty("current_session_context_class", "web"); sessionFactory= Fluently.Configure(cfg) .Mappings(m => m.FluentMappings .AddFromAssembly(typeof(SessionBuilder).Assembly)) .BuildSessionFactory(); } } #endregion #region Session在當前上下文的操作 private static void BindContext() { lock (_lock) { if (!CurrentSessionContext.HasBind(sessionFactory)) { CurrentSessionContext.Bind(sessionFactory.OpenSession()); } } } private static void UnBindContext() { lock (_lock) { if (CurrentSessionContext.HasBind(sessionFactory)) { CurrentSessionContext.Unbind(sessionFactory); } } } public static void CloseCurrentSession() { UnBindContext(); } public static ISession GetCurrentSession() { BindContext(); return sessionFactory.GetCurrentSession(); } #endregion #region 關閉SessionFactory(一般在應用程序結束時操作) public static void CloseSessionFactory() { if (!sessionFactory.IsClosed) { sessionFactory.Close(); } } #endregion #region 打開一個新的Session public static ISession OpenSession() { lock (_lock) { return sessionFactory.OpenSession(); } } #endregion }

 

使用這個類需要在應用程序啟動時初始化,調用代碼:SessionBuilder.Instance("web");,一般添加在Global.asax

    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // 在應用程序啟動時運行的代碼
            SessionBuilder.Instance("web");
        }

    }

 

使用時可調用SessionBuilder.GetCurrentSession()獲取上下文中的Session,以便實現自動打開關閉Session,

也可以SessionBuilder.OpenSession()得到一個普通的Session。


代碼映射:

public class Department
{
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
}

public class DepartmentMap:ClassMap<Department>
{
        public DepartmentMap()
        {
            Table("SYSDEPT");
            Id(p => p.ID).GeneratedBy.Sequence("SEQ_SYSDEPT");
            Map(p => p.Name);
        }
 }

這個使用單實體的例子非常簡單,相信差不多夠上手了,

更加復雜的配置有一定的學習曲線,推薦邊學邊用,以前用低端一點的ORM不也單實體在用么,

NH的好處就在於簡單起來可以很簡單地用,完全上手后又擁有其他一般ORM無法滿足的功能。

 

映射的重點:

實體類與數據庫之間需要有一個映射,所以我們建立一個DepartmentMap映射類,它需要繼承FluentNHibernate.Mapping.ClassMap<T>泛型類。

Table("SYSDEPT") 對應數據庫表名;

Id映射主鍵,這里使用sequence,其他還有許多辦法,比如GUID、自增長等。

Map映射,屬性名與數據庫字段相同就不需要另外聲明了。

 

測試一下,看看我們是否成功了。

ISession session = SessionBuilder.GetCurrentSession();
session.BeginTransaction();
Department obj = session.Load<Department>(102);
obj.Name = "新部門";
session.SaveOrUpdate(obj);
session.Transaction.Commit();


如果到這里已經能夠獲取到session了,那么恭喜你成功了,現在我們已經可以邊看官方文檔邊實戰了

如果你看不懂這段代碼,沒關系,可以邊看官方文檔邊練習了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM