扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:ghost 来源:CSDN 2007年9月24日
关键字: ghost NHibernate
1. 学习目的
学习Nhibernate基础知识。掌握Nhibernate的配置方法,实现对单表的简单操作,如:创建表,查询,添加,删除,修改。
2. 开发环境+前期准备
开发环境: windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition
前期准备: Nhibernate框架,我用的目前最新版NHibernate-1.2.0.CR1, 下载地址: http://downloads.sourceforge.net/nhibernate/NHibernate-1.2.0.CR1.msi?modtime=1172161735&big_mirror=0
3. 开发步骤:
1).双击下载下来的NHibernate-1.2.0.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文件。将下面代码粘贴到此文件:
12345678910111213141516 |
<?xml version="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;initial catalog=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> <!-- mapping files --> <mapping assembly="NhibernateSample1" /> </session-factory> </hibernate-configuration> |
该文件是Nhibernate的配置文件,其中connection.connection_string为数据库连接字符串,Dialect项因为我用的是SQL2005,所以为:MsSql2005Dialect注意:<mapping assembly=”NhibernateSample1”/>表示映射NhibernateSample1程序集下的所有类,所以以后不要需要Configuration.AddClass(..)了;
6).添加类文件:User.cs,添加代码:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
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
1234567891011 |
<?xml version="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,代码为:
123456789101112131415161718192021222324252627282930313233 |
using System;using System.Web;using NHibernate;using NHibernate.Cfg;namespace NhibernateSample1{ public sealed class NHibernateHelper { private static readonly ISessionFactory sessionFactory; static NHibernateHelper() { sessionFactory = new Configuration().Configure(@"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml").BuildSessionFactory(); } public static ISession GetCurrentSession() { ISession currentSession = sessionFactory.OpenSession(); return currentSession; } public static void CloseSessionFactory() { if (sessionFactory != null) { sessionFactory.Close(); } } }} |
注:因为我用的是单元测试,所以这里的配置文件路径写成固定的了。如果换成windows或者Web程序,可以直接去掉该路径。
8) 编写测试CRUD类:UserFixue
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
using System;using System.Collections.Generic;using System.Text;using NHibernate;using NHibernate.Cfg;using NHibernate.Tool.hbm2ddl;namespace NhibernateSample1{ public class UserFixure { private ISession session; public UserFixure() { } /**//// <summary> /// 创建表 /// </summary> public bool ExportTable() { try { Configuration cfg = new Configuration().Configure(@"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml"); session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); new SchemaExport(cfg).Create(true, true); transaction.Commit(); return true; } catch(Exception ex) { throw ex; } finally { session.Close(); } } /**//// <summary> /// 添加 /// </summary> public int Add() { try { User u = new User(); u.Name = Guid.NewGuid().ToString(); u.Pwd = "124"; session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); session.Save(u); transaction.Commit(); return u.Id; } catch (Exception ex) { throw ex; } finally { session.Close(); } } /**//// <summary> /// 更新 /// </summary> /// <param name="uid"></param> public bool Update(int uid) { try { session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); User u = 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 (Exception ex) { throw ex; } finally { session.Close(); } } /**//// <summary> /// 删除 /// </summary> /// <param name="uid"></param> /// <returns></returns> public bool Delete(int uid) { try { session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); User u = 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 (Exception ex) { throw ex; } finally { session.Close(); } } public System.Collections.IList Query() { try { session = NHibernateHelper.GetCurrentSession(); ITransaction transaction = session.BeginTransaction(); System.Collections.IList list= session.CreateQuery("select u from User as u").List(); transaction.Commit(); return list; } catch (Exception ex) { throw ex; } finally { session.Close(); } } }} |
9)创建新单元测试项目: TestProject1,添加NhibernateSample1的引用
10)创建单元测试类: UnitTest1.cs,并输入如下代码:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
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()] // public static void MyClassInitialize(TestContext testContext) { } // // 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码 // [ClassCleanup()] // public static void MyClassCleanup() { } // // 在运行每个测试之前使用 TestInitialize 运行代码 // [TestInitialize()] // public void MyTestInitialize() { } // // 在运行每个测试之后使用 TestCleanup 运行代码 // [TestCleanup()] // public void MyTestCleanup() { } // #endregion int uid; [TestMethod] public void TestMethod1() { UserFixure userFixure = new UserFixure(); Assert.IsTrue(userFixure.ExportTable()); } [TestMethod] public void TestMethod2() { UserFixure userFixure = new UserFixure(); uid = userFixure.Add(); Assert.IsTrue(uid>0); } [TestMethod] public void TestMethod3() { UserFixure userFixure = new UserFixure(); Assert.IsTrue(userFixure.Update(uid)); } [TestMethod] public void TestMethod4() { UserFixure userFixure = new UserFixure(); Assert.IsTrue(userFixure.Delete(uid)); } [TestMethod] public void TestMethod5() { UserFixure userFixure = new UserFixure(); Assert.IsTrue(userFixure.Query().Count>0); } }} |
11)在菜单-测试-加载元数据文件 选择NHibernateStudy1.vsmdi,然后按顺序执行TestMethod1-TestMethod5,全部成功!
4.总结
通过使用Nhibernate,基本上可以使开发人员不在接触繁琐的数据库表和数据库操作代码,您唯一需要关心的就是如何设计好类,让这些类满足您的业务需求。从扩展性来说Nhinernate具有非常好的扩展性。与代码生成比较,Nhibernate更改数据表结构对代码的影响要远远小于代码生成。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1733315
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者