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
- 下載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(非常的快)
- 入門教程
新建一個項目NHOne和測試程式,並且添加對於該項目的測試項目,項目架構如下:
劃重點:其中對於Nhibernate的配置文件(hibernate.cfg.xml與ClassMapping文件,對於生成的操作,必須選擇始終複製和嵌入式資源。(不然編譯調試的時候會出現bug,比如沒有Model Class的Mapping等等)。
- 測試項目詳解
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();
}
調試程式:
- 總結
NHibernate是C#程式員,參照Java的ORM框架Hibernate實現的一個開源項目,在C#中項目開發中非常的便捷高效,讓程式猿從複雜的SQL語句中解放出來,對於項目的模塊化非常好用。
測試項目的源代碼地址:
https://github.com/hbhzsysutengfei/NHibernateOne.git
參考文檔:
- NHibernate官方網站 http://nhibernate.info/
- 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的配置文件等等。