Nhibernate学习之起步篇-1

系统 1493 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条评论