Nhibernate 4.0 教程入門

来源:http://www.cnblogs.com/hbhzsysutengfei/archive/2016/11/18/6078898.html
-Advertisement-
Play Games

Nhibernate 4.0 教程 目錄 1. 下載Nhibernate 4.04. 1 2. 入門教程... 2 3. 測試項目詳解... 3 4. 總結... 7 附:關聯知識點... 7 知識點1:C#靜態構造函數... 7 知識點2:關於Visual Studio文件生成操作... 8 前言 ...


Nhibernate 4.0 教程

目錄

1.      下載Nhibernate 4.04. 1

2.      入門教程... 2

3.      測試項目詳解... 3

4.      總結... 7

附:關聯知識點... 7

知識點1:C#靜態構造函數... 7

知識點2:關於Visual Studio文件生成操作... 8

 

 

前言:

       為什麼會有這個框架?這就牽扯進了Java和C#的恩恩怨怨,Java是開源的面向對象語言的代表,圍繞Java的有不計其數的開源框架,其中ORM框架(不要問我什麼是ORM框架)中的最耀眼的代表就是Hibernate;C#也是Microsoft緊跟在Java後面推出的面向對象的語言,這兩個相似度太大了(我讀書自己學習的Java,後面C#就沒特殊的學習過,直接就進行拿來用了),.NET開發者也參照Hibernate開發了一個針對.NET平臺下的ORM 框架,也就是Nhibernate。

 

開發環境:

       Windows 7

       Visual Studio 2013

       Nhibernate 4.04

       Microsoft Sql Server 2012

  1. 下載Nhibernate 4.04

       直接下載 官網地址http://nhibernate.info/(自己下載網速真的好慢)

      NHibernate is a mature, open source object-relational mapper for the .NET framework. It's actively developed, fully featured and used in thousands of successful projects.

       官網介紹了Nhibernate是針對.NET框架的成熟的、開源的面向關係型資料庫映射(ORM).

       或者使用VS2013附帶的NuGet管理程式直接安裝(NuGet,.NET下麵一個開源的程式包管理工具):Install-Package Nhibernate(非常的快)

 

 

  1. 入門教程

       新建一個項目NHOne和測試程式,並且添加對於該項目的測試項目,項目架構如下:

 

 

劃重點:其中對於Nhibernate的配置文件(hibernate.cfg.xml與ClassMapping文件,對於生成的操作,必須選擇始終複製和嵌入式資源。(不然編譯調試的時候會出現bug,比如沒有Model Class的Mapping等等)。

  1. 測試項目詳解

3.1     初始化C#解決方案NHOne(控制台應用程式和對應的測試項目)

       給每一個項目添加Nhibernate引用,測試項目也需要(直接NuGet命令安裝即可)

3.2     編寫NHibernate配置文件

       在NHOne的根目錄下添加hibernate.cfg.xml文件(生成操作嵌入式資源和始終複製),在文檔屬性中架構選擇hibernate-configuration-2.2 & hibernate-mapping-2.2兩個文件,這樣編寫hibernate.cfg.xml就會有自動提示的功能(這兩個文件在我們解決方案NHOne的packages/Nhibernate目錄中)

 

 

hibernate.cfg.xml 具體內容如下:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

  <session-factory>

    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>

    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

    <property name="connection.connection_string">Data Source=localhost;user=sa;password=12345;Initial Catalog=test</property>

    <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>

    <property name="show_sql">true</property>

    <property name="hbm2ddl.auto">update</property>

   

    <!--Mapping files 嵌入式資源 表格table 名字不可以是user-->

    <mapping  assembly="NHOne"/>

  </session-factory>

 

</hibernate-configuration>

 

<mapping assembly=”NHOne”/> 這裡寫的是項目的名字,然後就會搜尋項目下麵所有的尾碼是.hbm.xml的文件,也可以手動自己添加,比較麻煩,有機會再詳細講解。

3.3     編寫Model Class “User”

         所有的屬性都是使用virtual來修飾(延遲載入有用),添加對應的get set方法

         在MSServer 中,user 是關鍵字,因此不能夠有user的表格,可以使用其他來代替

         在實際應用中,每一個model類,很可能需要提供Equals() HashCode() ToString()方法的重寫

namespace NHOne.Model

{

    public class User

    {

        private string id;

        private string username;

        private string password;

        private char gender; //"F" & "M"

        private int age;

        private string phone;

 

        public User()

        {

 

        }

 

        public User(string username, string password, char gender, int age, string phone)

        {

            this.username = username;

            this.password = password;

            this.gender = gender;

            this.age = age;

            this.phone = phone;

        }

 

        public User(string id, string username, string password, char gender, int age, string phone)

        {

            this.id = id;

            this.username = username;

            this.password = password;

            this.gender = gender;

            this.age = age;

            this.phone = phone;

        }

        public virtual string Id { get; set; }

        public virtual string Username { get; set; }

        public virtual string Password { get; set; }

        public virtual char Gender { get; set; }

        public virtual int Age { get; set; }

        public virtual string Phone { get; set; }

        public override bool Equals(object obj)

        {

            if (this == obj)

            {

                return true;

            }

            User user = obj as User;

            if (user == null)

            {

                return false;

            }

            else

            {

                return this.Username.Equals(user.Username);

            }

        }

 

        public override int GetHashCode()

        {

            return Username.GetHashCode();

        }

 

        public override string ToString()

        {

            return "id:" + Id + ";  Username:" + Username + ";  Password:" + Password + ";  Gender:" + Gender + ";  Age:" + Age + ";    Phone:" + Phone;

        }

    }

}

3.4  編寫Model的Mapping文件

    位於Mapping目錄下麵新建文件User.hbm.xml文件(嵌入式資源,添加文件的架構為hibernate-mapping-2.2.xml),紅色部分 assembly是項目的名稱,namespace是在項目中Model類的命名空間,如果省略的話,需要在後面的class name屬性中填寫完整的名字空間和類名。

註意table的名字不能寫成user,否則報錯,因為user是資料庫的關鍵字

內容如下:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHOne" namespace="NHOne.Model" default-lazy="true">

  <class name="User" table="client">

    <id name="Id">

      <column name="user_id" sql-type="char(32)" not-null="true"/>

      <generator class="uuid.hex"/>

    </id>

    <property name="Username" column="username"  not-null="true"/>

    <property name="Password" column="password" not-null="true" />

    <property name="Gender"   column="gender"   />

    <property name="Age"      column="age"      />

    <property name="Phone"    column="phone"    />

  </class>

</hibernate-mapping>

 

3.5    編寫NHibernate的幫助類,初始化NHibernate的環境,獲取Session

       在Util命名空間下,添加YangNHibernate的類,具體內容如下:

namespace NHOne.Util

{

    public class YangNHibernate

    {

        private static readonly  ISessionFactory sessionFactory;

        private static string HibernateHbmXmlFileName = "hibernate.cfg.xml";

        //private static ISession session

        static YangNHibernate()

        {

            sessionFactory = new Configuration().Configure().BuildSessionFactory();

        }

        public static ISessionFactory getSessionFactory()

        {

            return sessionFactory;

        }

        public static ISession getSession()

        {

            return sessionFactory.OpenSession();

        }

        public static void closeSessionFactory()

        {

            

        }

    }

}

 

3.6    編寫測試代碼

       在測試類中測試保存User到資料庫,使用事務的機制

        [TestMethod]

        public void TestSaveUser()

        {

            User user = createUser();

            ISession session  = YangNHibernate.getSession();

            ITransaction tx = session.BeginTransaction();

            session.Save(user);

            tx.Commit();

            session.Close();

       

        }

 

調試程式:

 

 

 

  1. 總結

       NHibernate是C#程式員,參照Java的ORM框架Hibernate實現的一個開源項目,在C#中項目開發中非常的便捷高效,讓程式猿從複雜的SQL語句中解放出來,對於項目的模塊化非常好用。

       測試項目的源代碼地址:

                 https://github.com/hbhzsysutengfei/NHibernateOne.git

參考文檔:

  1. NHibernate官方網站 http://nhibernate.info/
  2. MSDN for C#:https://msdn.microsoft.com/zh-cn/library/k9x6w0hc(v=vs.120).aspx

附:關聯知識點

知識點1:C#靜態構造函數

C#關於靜態構造函數的知識,自動調用初始化靜態的成員屬性,尤其是readonly修飾的靜態屬性,與Java中的靜態代碼塊類似。

參考MSDN給出的解釋:

       A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

https://msdn.microsoft.com/zh-cn/library/k9x6w0hc(v=vs.120).aspx

       因為靜態構造函數是.NET自動調用的,因此改代碼塊就無需使用修飾符修飾。

關於C#靜態構造函數的特征,具體如下:

       A static constructor does not take access modifiers or have parameters.

       A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

       A static constructor cannot be called directly.

       The user has no control on when the static constructor is executed in the program.

       A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

       Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

       If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

 

知識點2:關於Visual Studio文件生成操作

Visual Studio生成操作有以下幾個選項:

       Non(無):也就是在項目生成的時候不進行任何的操作,在生成的目錄中沒有此文件,一般用於項目描述文件.

       Content(內容):也就是將文件直接複製到輸出目錄中,一般用於html等靜態文件.

       Compile(編譯):編譯代碼文件,通常的代碼文件需要編譯

       Embedded Resource(嵌入式資源):將該文件作為DLL或可執行文件嵌入到主目錄中,通常用於資源文件,比如Nhibernate的配置文件等等。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在Ubuntu支持中文後(方法見上篇文章),預設是UTF-8編碼,而Windows中文版預設是GBK編碼。為了一致性,通常要把Ubuntu的預設編碼改為GBK。當然你也可以不改,但這會導致我們在兩個系統之間共用文件變得非常不方便,Samba共用的文件也總會有亂碼出現。總不能每次傳完文件都人肉轉碼一次 ...
  • SVN,大家都熟悉,做項目都知道,不知道你有沒有遇到每次提交的代碼的時候,都會把bin和obj自動生成的文件夾提交SVN伺服器上 其實這裡都不需要提交,每次生成都提交,可能還會容易衝突,如何不讓bin和obj不提交呢? 選擇不要提交文件 這樣就OK,如果還不行,就刷新該文件夾目錄,如果還是不行,在操 ...
  • 使用 async & await 一步步將同步代碼轉換為非同步編程 【博主】反骨仔 【出處】http://www.cnblogs.com/liqingwen/p/6079707.html 序 上次,博主通過《利用 async & await 的非同步編程》一文介紹了 async & await 的基本用 ...
  • 前言 開發授權服務框架一般使用OAuth2.0授權框架,而開發Webapi的授權更應該使用OAuth2.0授權標準,OAuth2.0授權框架文檔說明參考:https://tools.ietf.org/html/rfc6749 .NET Core開發OAuth2的項目需要使用IdentityServe ...
  • 在本機跑過10000萬個併發連接,用的jmeter,jmeter占用了1.4G左右的記憶體、90%多的CPU,我也不知道為什麼這麼耗資源,筆記本勉強還能工作。 現在模擬的是15個客戶端,100毫秒發送一次數據,效果如下: ...
  • .NET Core配置文件 在以前.NET中配置文件都是以App.config / Web.config等XML格式的配置文件,而.NET Core中建議使用以JSON為格式的配置文件,因為使用起來更加方面靈活,而且可以使用.NET Core中的DI註入配置數據。 使用: 配置文件appsettin ...
  • RSA: 獲取RSA實例: 獲取公鑰: 獲取私鑰: ...
  • Json.NET: 獲取類實例對應的jtoken:JObject.FromObject() 獲取數組實例對應的jtoken:JArray.FromObject() ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...