亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

Nhibernate學習之起步篇-1

系統 2317 0

1.學習目的
學習Nhibernate基礎知識。掌握Nhibernate的配置方法,實現對單表的簡單操作,如:創建表,查詢,添加,刪除,修改。
2.開發環境+前期準備
開發環境: windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition
前期準備: Nhibernate框架,我用的目前最新版NHibernate-<chsdate year="1899" month="12" day="30" islunardate="False" isrocdate="False" w:st="on">1.2.0</chsdate>.CR1, 下載地址: http://downloads.sourceforge.net/nhibernate/NHibernate-1.2.0.CR1.msi?modtime=1172161735&big_mirror=0
3.開發步驟:
1).雙擊下載下來的NHibernate-<chsdate year="1899" month="12" day="30" islunardate="False" isrocdate="False" w:st="on">1.2.0</chsdate>.CR1.msi,將其安裝到某個目錄,我的目錄為: E:/download project/orm/nhibernate.,打開該目錄,即可以看到bin,doc,src三個子目錄,分別為Realse好的dll或者exe目錄,文檔說明目錄,和源程序目錄.
2).打開visual studio 2005,創建類庫項目NhibernateSample1
3).在解決方案管理其中,右鍵點擊引用-添加引用,在選項卡種選擇瀏覽,設定查找范圍為:E:/download project/orm/nhibernate/bin, 添加對 Nhibernate.dll,log4net.dll, Iesi.Collections, HashCodeProvider 四個 dll 的引用 .
4).打開SQL Server Management Studio,創建數據庫nhibernate。
5).在解決方案管理器中添加hibernate.cfg.xml文件。將下面代碼粘貼到此文件:

<? xmlversion="1.0"encoding="utf-8" ?>
< hibernate-configuration xmlns ="urn:nhibernate-configuration-2.2" >
< session-factory name ="NHibernate.Test" >
<!-- properties -->
< property name ="connection.provider" > NHibernate.Connection.DriverConnectionProvider </ property >
< property name ="connection.driver_class" > NHibernate.Driver.SqlClientDriver </ property >
< property name ="connection.connection_string" > Server=127.0.0.1;initialcatalog=nhibernate;uid=sa;pwd=123; </ property >
< property name ="show_sql" > false </ property >
< property name ="dialect" > NHibernate.Dialect.MsSql2005Dialect </ property >
< property name ="use_outer_join" > true </ property >
<!-- mappingfiles -->
< mapping assembly ="NhibernateSample1" />
</ session-factory >
</ hibernate-configuration >

該文件是 Nhibernate 的配置文件,其中 connection.connection_string 為數據庫連接字符串, Dialect 項因為我用的是 SQL2005, 所以為 :MsSql2005Dialect 注意 :<mapping assembly=”NhibernateSample<chmetcnv tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="”" w:st="on">1”</chmetcnv>/> 表示映射 NhibernateSample1 程序集下的所有類,所以以后不要需要 Configuration.AddClass(..) 了;

6). 添加類文件 :User.cs, 添加代碼 :

using System;
using System.Collections.Generic;
using System.Text;

namespace NhibernateSample1
{
public class User
{
private int _id;
private string _name;
private string _pwd;
/**/ /// <summary>
/// 編號
/// </summary>

public virtual int Id
{
get
{
return _id;
}

set
{
_id
= value;
}

}


/**/ /// <summary>
/// 名稱
/// </summary>

public virtual string Name
{
get
{
return _name;
}

set
{
_name
= value;
}

}


/**/ /// <summary>
/// 密碼
/// </summary>

public virtual string Pwd
{
get
{
return _pwd;
}

set
{
_pwd
= value;
}

}

}

}

6). 編寫 User 類的映射配置文件 :User.hbm.xml

<? xmlversion="1.0"encoding="utf-8" ?>
< hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2" >
< class name ="NhibernateSample1.User,NhibernateSample1" table ="Users" lazy ="false" >
< id name ="Id" column ="Id" unsaved-value ="0" >
< generator class ="native" />
</ id >
< property name ="Name" column ="Name" type ="string" length ="64" not-null ="true" unique ="true" ></ property >
< property name ="Pwd" column ="Pwd" type ="string" length ="64" not-null ="true" ></ property >
</ class >
</ hibernate-mapping >

注意:該映射文件的屬性中的生成操作必須為:嵌入的資源.

7).編寫管理ISession對象的輔助類: NHibernateHelper.cs,代碼為:

using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace NhibernateSample1
{
public sealed class NHibernateHelper
{
private static readonly ISessionFactorysessionFactory;

static NHibernateHelper()
{
sessionFactory
= new Configuration().Configure( @" E:/myproject/nhibernatestudy/simle1/NHibernateStudy1/NhibernateSample1/hibernate.cfg.xml " ).BuildSessionFactory();
}


public static ISessionGetCurrentSession()
{
ISessioncurrentSession
= sessionFactory.OpenSession();
return currentSession;
}


public static void CloseSessionFactory()
{
if (sessionFactory != null )
{
sessionFactory.Close();
}

}

}

}

: 因為我用的是單元測試,所以這里的配置文件路徑寫成固定的了。如果換成 windows 或者 Web 程序,可以直接去掉該路徑。

8) 編寫測試 CRUD :UserFixue

using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
namespace NhibernateSample1
{
public class UserFixure
{
private ISessionsession;
public UserFixure()
{

}

/**/ /// <summary>
/// 創建表
/// </summary>

public bool ExportTable()
{
try
{
Configurationcfg
= new Configuration().Configure( @" E:/myproject/nhibernatestudy/simle1/NHibernateStudy1/NhibernateSample1/hibernate.cfg.xml " );
session
= NHibernateHelper.GetCurrentSession();
ITransactiontransaction
= session.BeginTransaction();
new SchemaExport(cfg).Create( true , true );
transaction.Commit();
return true ;
}

catch (Exceptionex)
{
throw ex;
}

finally
{
session.Close();
}

}

/**/ /// <summary>
/// 添加
/// </summary>

public int Add()
{
try
{
Useru
= new User();
u.Name
= Guid.NewGuid().ToString();
u.Pwd
= " 124 " ;
session
= NHibernateHelper.GetCurrentSession();
ITransactiontransaction
= session.BeginTransaction();
session.Save(u);
transaction.Commit();
return u.Id;
}

catch (Exceptionex)
{
throw ex;
}

finally
{
session.Close();
}

}

/**/ /// <summary>
/// 更新
/// </summary>
/// <paramname="uid"></param>

public bool Update( int uid)
{
try
{
session
= NHibernateHelper.GetCurrentSession();
ITransactiontransaction
= session.BeginTransaction();
Useru
= session.Load( typeof (User),uid) as User;
if (u != null )
{
u.Name
= " updatedName " ;
session.SaveOrUpdate(u);
transaction.Commit();
u
= session.Load( typeof (User),uid) as User;
if (u.Name == " updatedName " )
{
return true ;
}

}

return false ;
}

catch (Exceptionex)
{
throw ex;
}

finally
{
session.Close();
}

}

/**/ /// <summary>
/// 刪除
/// </summary>
/// <paramname="uid"></param>
/// <returns></returns>

public bool Delete( int uid)
{
try
{
session
= NHibernateHelper.GetCurrentSession();
ITransactiontransaction
= session.BeginTransaction();
Useru
= session.Get( typeof (User),uid) as User;
if (u != null )
{
session.Delete(u);
transaction.Commit();
u
= session.Get( typeof (User),uid) as User;
if (u == null )
{
return true ;
}

}

return false ;
}

catch (Exceptionex)
{
throw ex;
}

finally
{
session.Close();
}

}

public System.Collections.IListQuery()
{
try
{
session
= NHibernateHelper.GetCurrentSession();
ITransactiontransaction
= session.BeginTransaction();
System.Collections.IListlist
= session.CreateQuery( " selectufromUserasu " ).List();
transaction.Commit();
return list;
}

catch (Exceptionex)
{
throw ex;
}

finally
{
session.Close();
}

}

}

}


9) 創建新單元測試項目 : TestProject1, 添加 NhibernateSample1 的引用
10 )創建單元測試類 : UnitTest1.cs, 并輸入如下代碼 :
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NhibernateSample1;

namespace TestProject1
{
/**/ /// <summary>
/// UnitTest1的摘要說明
/// </summary>

[TestClass]
public class UnitTest1
{
public UnitTest1()
{
//
// TODO:在此處添加構造函數邏輯
//
}


其他測試屬性 #region 其他測試屬性
//
// 您可以在編寫測試時使用下列其他屬性:
//
// 在運行類中的第一個測試之前使用ClassInitialize運行代碼
// [ClassInitialize()]
// publicstaticvoidMyClassInitialize(TestContexttestContext){}
//
// 在類中的所有測試都已運行之后使用ClassCleanup運行代碼
// [ClassCleanup()]
// publicstaticvoidMyClassCleanup(){}
//
// 在運行每個測試之前使用TestInitialize運行代碼
// [TestInitialize()]
// publicvoidMyTestInitialize(){}
//
// 在運行每個測試之后使用TestCleanup運行代碼
// [TestCleanup()]
// publicvoidMyTestCleanup(){}
//
#endregion


int uid;
[TestMethod]
public void TestMethod1()
{
UserFixureuserFixure
= new UserFixure();
Assert.IsTrue(userFixure.ExportTable());
}

[TestMethod]
public void TestMethod2()
{
UserFixureuserFixure
= new UserFixure();
uid
= userFixure.Add();
Assert.IsTrue(uid
> 0 );
}

[TestMethod]
public void TestMethod3()
{
UserFixureuserFixure
= new UserFixure();
Assert.IsTrue(userFixure.Update(uid));
}

[TestMethod]
public void TestMethod4()
{
UserFixureuserFixure
= new UserFixure();
Assert.IsTrue(userFixure.Delete(uid));
}

[TestMethod]
public void TestMethod5()
{
UserFixureuserFixure
= new UserFixure();
Assert.IsTrue(userFixure.Query().Count
> 0 );
}

}

}


11 )在菜單 - 測試 - 加載元數據文件 選擇 NHibernateStudy1.vsmdi ,然后按順序執行 TestMethod1-TestMethod5, 全部成功 !
4. 總結
通過使用 Nhibernate ,基本上可以使開發人員不在接觸繁瑣的數據庫表和數據庫操作代碼,您唯一需要關心的就是如何設計好類,讓這些類滿足您的業務需求。從擴展性來說 Nhinernate 具有非常好的擴展性。與代碼生成比較, Nhibernate 更改數據表結構對代碼的影響要遠遠小于代碼生成。
如果您想下載Demo: /Files/jillzhang/simle.rar

Nhibernate學習之起步篇-1


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 成人影院午夜久久影院 | 精品一二区 | 日韩午夜在线视频不卡片 | 男人的天堂在线精品视频 | 老司机午夜网站 | 亚洲欧美一区二区久久 | 亚洲女人逼 | 久久久网久久久久合久久久久 | 蜜桃综合| 自拍在线视频 | 天天做天天添婷婷我也去 | 精品久久久久久久99热 | 久久er热这里只有精品免费 | 一级视频片 | 欧洲一级做a爱在线观看 | 日韩精品在线视频观看 | 5g国产精品影院天天5g天天爽 | 亚洲精品国产福利一区二区三区 | 国产看色免费 | 天天夜天干天天爽 | 国产高清不卡一区二区 | 一级毛片在线播放免费 | 91亚洲影院| 男人你懂的网站 | 日韩精品一区二区三区在线观看l | 视频播放在线观看精品视频 | 另类尿喷潮videofree | 亚洲国产精品自产在线播放 | 久久久在线 | 全部费免一级毛片不收费 | 亚洲网址在线观看 | 亚洲欧美中文字幕高清在线一 | 伊人久久亚洲综合天堂 | 99久9在线 | 免费 | 奇米影视7777久久精品 | 一区二区三区在线免费看 | 久久精品国产精品亚洲综合 | 日韩欧美一二三 | 亚洲精品色综合久久久 | 不卡的毛片 | 欧美不卡视频 |