NHibernate初学体验记
測試環(huán)境:單機安裝Win2003SP2 + SQL2000 + .NET2.0 + VS2005
一、下載安裝NHibernate
下載地址:http://sourceforge.net/project/showfiles.php?group_id=73818
運行安裝程序NHibernate-1.2.1.GA.msi,默認情況下“C:"Program Files"NHibernate”目錄下。
二、準備數據庫
1.在SQL Server2000下創(chuàng)建NHibernate數據庫;
2.執(zhí)行如下SQL語句創(chuàng)建數據表users:
| use NHibernate go CREATE TABLE users ( ?LogonID nvarchar(20) NOT NULL default '0', ?Name nvarchar(40) default NULL, ?Password nvarchar(20) default NULL, ?EmailAddress nvarchar(40) default NULL, ?LastLogon datetime default NULL, ?PRIMARY KEY?(LogonID) ) go |
三、開發(fā)程序
1.在VS2005中新建類庫項目NHibernate.Examples,同時選中“創(chuàng)建解決方案目錄”復選框。
???
<?XML:NAMESPACE PREFIX = V />????2.在NHibernate.Examples類庫項目創(chuàng)建類文件User.cs,內容如下。(注:一個User對象對應數據表users中的一條記錄。)
| using System; namespace NHibernate.Examples.QuickStart { ??? public class User ??? { ??????? private string id; ??????? private string userName; ??????? private string password; ??????? private string emailAddress; ??????? private DateTime lastLogon; ??????? public User() ??????? { ??????? } ??????? 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; } ??????? } ??? } } |
3.在NHibernate.Examples類庫項目創(chuàng)建映射文件User.hbm.xml,并將文件的“生成操作”屬性設置為“嵌入的資源”(如圖),映射文件將成為裝配件的一部分。
????????????
| <?xml version="1.0" encoding="utf-8" ?> |
讓我們來看看User.hbm.xml文件中讓我們感興趣的某些行。第一個有趣的標簽是class。這里我們將映射類型名稱(類名和裝配件)到我們數據庫中的User表,這里和Hibernate有一點點的不同。你將不得不告訴NHibernate從何處提取對象。在這個例子里我們從裝配件NHibernate.Examples裝載類NHibernate.Examples.QuickStart.User 。NHibernate 遵循和.Net Framework同樣的規(guī)則來加載類型。因此如果你在如何指定類型的方面有些混淆,請參看.Net Framework SDK。
讓我們先跳過id標簽,來討論property標簽。簡要看一下,你將發(fā)現NHibernate所要做的工作。name屬性的值正是我們.Net 類的屬性,column屬性值將是我們數據庫里的字段。type屬性是可選的(如果你不標明,NHibernate將利用反射進行最佳的推測)。
好了,讓我們回到標簽id, 你可以猜測到這個標簽將是映射數據庫表的主鍵,的確如此,id標簽的組成和我們剛才看的property標簽是相似的。我們映射屬性到目標數據庫的字段。
內嵌的generator 標簽告訴NHibernate 如何生成主鍵(它將恰當的為你生成主鍵,不管你指定何種類型,但你必須告訴它)。在我們的例子里,我們設定為assigned,意味著我們對象將自己生成主鍵(畢竟User對象常常需要一個UserID)。如果你執(zhí)意要NHiberante為你生成主鍵,你感興趣于設定uuid.hex和uuid.string(從文檔中獲取更多信息)
提示:如果你僅僅是改變映射文件,你不能使用build 而應該Rebuild項目。Visual Studio.Net 不會重新編譯有改變的映射文件。
4.新建一個Windows應用程序項目NHibernateQuickStart,并添入已有的解決方案。
???
5.在項目NHibernateQuickStart中添加對NHibernate.dll的引用(默認安裝情況下在“C:"Program Files"NHibernate"bin"net-2.0"NHibernate.dll”)。
???
6.在項目NHibernateQuickStart中添加對NHibernate.Examples類庫項目的引用:
???
7. 在項目NHibernateQuickStart中添加應用程序配置文件App.config,內容如下:(告訴NHibernate 去哪里連接數據庫以及數據庫的相關配置)
| <?xml version="1.0" encoding="utf-8" ?> <configuration> ?<configSections> ??? <section ????? name="nhibernate" ????? type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ??? /> ?</configSections> ?<nhibernate> ??? <add key="hibernate.connection.provider" ????? value="NHibernate.Connection.DriverConnectionProvider" ??? /> ??? <add key="hibernate.dialect" ????? value="NHibernate.Dialect.MsSql2000Dialect" ??? /> ??? <add key="hibernate.connection.driver_class" ????? value="NHibernate.Driver.SqlClientDriver" ??? /> ??? <add key="hibernate.connection.connection_string" ????? value="Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI" ??? /> ?</nhibernate> </configuration> |
8.開始編寫寫入數據的代碼。
(1)在項目NHibernateQuickStart中Form1窗體上添一個按鈕button1,雙擊button1進入代碼編輯界面,我們將在button1_Click事件中編寫代碼。
(2)在代碼中添加using聲明:
| using NHibernate; using NHibernate.Cfg; using NHibernate.Examples.QuickStart; |
(3)button1_Click事件代碼如下:
| private void button1_Click(object sender, EventArgs e) ??????? { ??????????? Configuration cfg = new Configuration(); ??????????? cfg.AddAssembly("NHibernate.Examples"); ??????????? ISessionFactory factory = cfg.BuildSessionFactory(); ??????????? ISession session = factory.OpenSession(); ??????????? ITransaction transaction = session.BeginTransaction(); ??????????? User newUser = new User(); ??????????? newUser.Id = "joe_cool_test"; ??????????? newUser.UserName = "Joseph Cool"; ??????????? newUser.Password = "abc123"; ??????????? newUser.EmailAddress = "joe@cool.com"; ??????????? newUser.LastLogon = DateTime.Now; ??????????? // Tell NHibernate that this object should be saved ??????????? session.Save(newUser); ??????????? // commit all of the changes to the DB and close the ISession ??????????? transaction.Commit(); ??????????? session.Close(); ??????? } |
(4)編譯整個解決方案。執(zhí)行生成的EXE文件NHibernateQuickStart.exe,點擊button1。之后,打開數據庫users表,如果產生了一條記錄,則成功!
本項目源碼下載:NHibernateQuickStart1.rar
??? ===================================================================================
另外,本人還寫了一個復雜點的示例,包含了增加、修改、刪除、顯示記錄的操作:
??? 源碼下載:NHibernateQuickStart2.rar。看了這個代碼你會發(fā)現項目中充斥了如下類似的代碼:
| ??????????? Configuration cfg = new Configuration(); ??????????? cfg.AddAssembly("NHibernate.Examples"); ??????????? ISessionFactory factory = cfg.BuildSessionFactory(); ??????????? ISession session = factory.OpenSession(); ??????????? ITransaction transaction = session.BeginTransaction(); |
如何解決這個問題呢?以后再探討吧J
===================================================================================
推薦閱讀《Hibernate Quickly中文版》一書,雖然是針對Java的,但是思想是相通的,NHibernate本源于Hibernate,看了之后會Hibernate有全面深入的認識。
其它資料:
Hibernate官方網站:http://www.hibernate.org
NHibernate論壇:http://www.okec.cn
renrenqq的blog(有豐富的ORM資料):http://www.cnblogs.com/renrenqq
??? (注:本人參考NHibernate官方快速指南未能測試成功,后整理本篇文檔,參考了譯文:http://www.okec.cn/htm_data/7/0709/194.html)
=====================================================================================================
參考NHibernate官方快速指南編寫代碼遇到的問題:
From:http://hi.baidu.com/zsea/blog/item/7d999e3d8a54c203baa1678d.html
一、Test.Model.Person.hbm.xml(2,2): XML validation error: 未能找到元素“urn:nhibernate-mapping-2.0:hibernate-mapping”的架構信息。
?????? 將2.0改為2.2
二、 The following types may not be used as proxies:
???????? Test.Model.Person: method set_Id should be virtual
???????? Test.Model.Person: method get_Name should be virtual
???????? Test.Model.Person: method set_Name should be virtual
???????? Test.Model.Person: method get_Id should be virtual
???????? 類配置文件中Class的Lazy改為false
???????? 網上搜到的三種解決方案:
????????1.?? You can follow the advice of the exception and add "virtual" to all of your properties, and make sure your class is non-sealed. Obviously you'll want to do this if you think you might want to take advantage of the lazy-initializing proxy feature.?? However, changing your classes may not be practical or advisable if you have a legacy codebase, or it may just bother you that a "transparent" persistence framework is dictating how you design certain aspects of your value classes.?? That's where Options 2 and 3 come in.?? Both of those involve changing back to the old behavior.
???? name="NorthwindClasses.Category, NorthwindClasses"
???? table="Categories"
???? lazy="false"
> 3.??To change the lazy-initialization proxy setting for all classes in a given mapping file, you can add a "default-lazy='false'" attribute to the <hibernate-mapping> element, as follows: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0" default-lazy="false"> Unfortunately, Option 3 doesn't really help you much if you do one <class> mapping per <hibernate-mapping> file, a practice which I personally follow and recommend.?? It's too bad, but there doesn't seem to be any way to set this default in the <nhibernate> global configuration.?? But if you do happen to have all of your <class>'s in one .hbm.xml file, "default-lazy" can help you out.
轉載于:https://www.cnblogs.com/yangjunwl/articles/1112483.html
總結
以上是生活随笔為你收集整理的NHibernate初学体验记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [14] 薪酬迅速翻倍的13条跳槽原则
- 下一篇: 你印象中的高仓健在哪一部电影?