关于NHibernate的ORM映射可以通过Hbm映射文件来完成,代码生成工具使得这一步骤变得简化;而NHibernate3.2版本集成Mapping-By-Code(代码映射),不同于其他映射方式,具体可以参考李永京博客(NHibernate剖析:Mapping篇之Mapping-By-Code),此处不再赘述;Mapping-By-Code采用手动配置实体映射,顾名思义会增加程序代码编写量,而且数据库表关系映射(ont-to-many, many-to-one,many-to-many)编写比较复杂,所以我摒弃这种方式而采用了Mindscape NHibernate Model Designer设计工具。为此,首先介绍一下NHibernate数据访问层,Web.config文件配置、NHibernate Configuration类和Session Manager类。

Web.config

隐藏行号 复制代码 ?
  1. <appSettings>
    
  2.     <add key="ClientValidationEnabled" value="true"/>
    
  3.     <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    
  4.     <add key="TESZConnectionString" value="User id=sa;Password=sql123!!;data source=localhost;persist security info=True;initial catalog=TESZ_NEW;"/>
    
  5.   </appSettings>
    

Web.config是采用appSettings来设置数据库connection string,而非NHiberate标准配置。

NHibernateCfg.cs

隐藏行号 复制代码 ?
  1. public static class NHibernateCfg
    
  2.     {
    
  3.         private static string _ConnectionString;
    
  4.         public static Configuration GetConfiguration()
    
  5.         {
    
  6.             _ConnectionString = System.Configuration.ConfigurationManager.AppSettings["TESZConnectionString"].ToString();
    
  7.             var configure = new Configuration();
    
  8.             configure.SessionFactoryName("TESZ_NEW");
    
  9.             configure.DataBaseIntegration(db =>
    
  10.             {
    
  11.                 db.Dialect<MsSql2005Dialect>();
    
  12.                 db.Driver<SqlClientDriver>();
    
  13.                 db.ConnectionString = _ConnectionString;
    
  14.             });
    
  15.             ApplyConfiguration(configure);
    
  16.             return configure;
    
  17.         }
    
  18.         public static void ApplyConfiguration(Configuration configuration)
    
  19.         {
    
  20.             configuration.AddXml(Location_Country.MappingXml.ToString());
    
  21.             configuration.AddXml(Location_StateProvince.MappingXml.ToString());
    
  22.             configuration.AddXml(Location_City.MappingXml.ToString());
    
  23.             configuration.AddXml(Common_Date.MappingXml.ToString());
    
  24.             configuration.AddXml(System_Purview.MappingXml.ToString());
    
  25.             configuration.AddAssembly(typeof(NHibernateCfg).Assembly);
    
  26.         }
    
  27.     }
    

此处在NHibernateCfg类中进行数据库连接属性的配置,并把由Mindscape NHibernate Model Designer工具生成的实体类中的MappingXml配置给Configuration,来进行ORM映射。

SessionManager.cs

隐藏行号 复制代码 ?
  1. /// <summary>
    
  2.     /// 使用 NHibernate 操作数据库的Session
    
  3.     /// </summary>
    
  4.     public sealed class SessionManager
    
  5.     {
    
  6.         private const string CurrentSessionKey = "nhibernate.current_session";
    
  7.         private static readonly ISessionFactory sessionFactory;
    
  8.         private static Configuration conf = null;
    
  9.         private static ModelMapper mapper = null;
    
  10.         static SessionManager()
    
  11.         {
    
  12.             mapper = new ModelMapper();
    
  13.             if (sessionFactory == null)
    
  14.             {
    
  15.                 conf = NHibernateCfg.GetConfiguration();
    
  16.                 sessionFactory = conf.BuildSessionFactory();
    
  17.             }
    
  18.         }
    
  19.         public static ISession GetCurrentSession()
    
  20.         {
    
  21.             HttpContext context = HttpContext.Current;
    
  22.             ISession currentSession = context.Items[CurrentSessionKey] as ISession;
    
  23.             if (currentSession == null)
    
  24.             {
    
  25.                 currentSession = sessionFactory.OpenSession();
    
  26.                 context.Items[CurrentSessionKey] = currentSession;
    
  27.             }
    
  28.             else
    
  29.             {
    
  30.                 currentSession = sessionFactory.OpenSession();
    
  31.             }
    
  32.             return currentSession;
    
  33.         }
    
  34.         public static void CreateDataTable()
    
  35.         {
    
  36.             //配置数据库a
    
  37.             SchemaMetadataUpdater.QuoteTableAndColumns(conf);
    
  38.             //创建数据库
    
  39.             new SchemaExport(conf).Create(false, true);
    
  40.         }
    
  41.         public static void DropDataTable()
    
  42.         {
    
  43.             //配置数据库
  44.             SchemaMetadataUpdater.QuoteTableAndColumns(conf);
    
  45.             //删除数据库
  46.             new SchemaExport(conf).Drop(false, true);
    
  47.         }
    
  48.         public static void CloseSession()
    
  49.         {
    
  50.             HttpContext context = HttpContext.Current;
    
  51.             ISession currentSession = context.Items[CurrentSessionKey] as ISession;
    
  52.             if (currentSession == null)
    
  53.             {
    
  54.                 // No current session
    
  55.                 return;
    
  56.             }
    
  57.             currentSession.Close();
    
  58.             context.Items.Remove(CurrentSessionKey);
    
  59.         }
    
  60.         public static void CloseSessionFactory()
    
  61.         {
    
  62.             if (sessionFactory != null)
    
  63.             {
    
  64.                 sessionFactory.Close();
    
  65.             }
    
  66.         }
    
  67.     }
    

以上是NHibernate Session管理类。

接着就该讲如何通过Mindscape NHibernate Model Designer工具生成实体类了。具体方法是:选择新建项,在“已安装的模版”的数据分类下选择NHibernate Model,然后从“服务器资源管理器”中拖拽表至Mindscape设计器中,并可以通过NHibernate Model工具栏的Model->Entities->实体类的属性进行实体类的更名。生成的实体类如下图:

Location_Country.cs

隐藏行号 复制代码 ?
  1. [System.CodeDom.Compiler.GeneratedCode("NHibernateModelGenerator", "1.0.0.0")]
    
  2.   public partial class Location_Country
    
  3.   {
    
  4.     public virtual int CountryId { get; set; }
    
  5.     public virtual string CountryCode1 { get; set; }
    
  6.     public virtual string CountryCode2 { get; set; }
    
  7.     public virtual System.Nullable<System.DateTime> ModifiedDate { get; set; }
    
  8.     public virtual string ModifiedBy { get; set; }
    
  9.     public virtual string CountryDialCode { get; set; }
    
  10.     public virtual string CountryName { get; set; }
    
  11.     private IList<Location_StateProvince> _locationStateProvinces = new List<Location_StateProvince>();
    
  12.     public virtual IList<Location_StateProvince> LocationStateProvinces
    
  13.     {
    
  14.       get { return _locationStateProvinces; }
    
  15.       set { _locationStateProvinces = value; }
    
  16.     }
    
  17.     static partial void CustomizeMappingDocument(System.Xml.Linq.XDocument mappingDocument);
    
  18.     public static System.Xml.Linq.XDocument MappingXml
    
  19.     {
    
  20.       get
    
  21.       {
    
  22.         var mappingDocument = System.Xml.Linq.XDocument.Parse(@"<?xml version='1.0' encoding='utf-8' ?>
    
  23. <hibernate-mapping xmlns='urn:nhibernate-mapping-2.2'
    
  24.                    assembly='" + typeof(Location_Country).Assembly.GetName().Name + @"'
    
  25.                    namespace='TESZ.Data.Model'
    
  26.                    >
    
  27.   <class name='Location_Country'
    
  28.          table='`Location_Country`'
    
  29.          >
    
  30.     <id name='CountryId'
    
  31.         column='`CountryId`'
    
  32.         >
    
  33.       <generator class='identity'>
    
  34.       </generator>
    
  35.     </id>
    
  36.     <property name='CountryCode1'
    
  37.               column='`CountryCode1`'
    
  38.               />
    
  39.     <property name='CountryCode2'
    
  40.               column='`CountryCode2`'
    
  41.               />
    
  42.     <property name='ModifiedDate'
    
  43.               column='`ModifiedDate`'
    
  44.               />
    
  45.     <property name='ModifiedBy'
    
  46.               column='`ModifiedBy`'
    
  47.               />
    
  48.     <property name='CountryDialCode'
    
  49.               column='`CountryDialCode`'
    
  50.               />
    
  51.     <property name='CountryName'
    
  52.               column='`CountryName`'
    
  53.               />
    
  54.     <bag name='LocationStateProvinces'
    
  55.           inverse='true'
    
  56.           >
    
  57.       <key column='`CountryId`' />
    
  58.       <one-to-many class='Location_StateProvince' />
    
  59.     </bag>
    
  60.   </class>
    
  61. </hibernate-mapping>");
    
  62.         CustomizeMappingDocument(mappingDocument);
    
  63.         return mappingDocument;
    
  64.       }
    
  65.     }
    
  66.   }
    

此处请注意一下三项(以上实体类已经经过修改):

    1.自动生成的实体类文件中,需要删除ConfigurationHelper类,因为之前在NHibernateCfg中已经配置MappingXml;

2.实体类中的internal static System.Xml.Linq.XDocument MappingXml的internal需改为public,否则NHibernateCfg的configuration.AddXml(Location_Country.MappingXml.ToString());会报错;

    3.如果数据表有one-to-many关系,则必有many-to-one关系,MappingXml中会自动生成;比如<many-to-one name='Country' class='Location_Country' column='`CountryId`' />,则需要在其中添加lazy='false' 属性,否则实体类Location_StateProvince通过mant-to-one关系访问实体Location_Country时会抛出异常;

4.如果数据表结构发生变化,可以在Mindscape设计器中以Update Model from Database来更新实体类,之后还要重复以上三个步骤。

  如需自动生成one-to-many和many-to-one关系,则在进行数据库创建时,要配置数据表对应关系,如下图:

数据表关系设计

  如此,就完成了实体类的编写。

  最后简单讲一下数据访问接口和接口实现,在这儿我就不仔细说了,直接贴代码吧!

ILocation_CountryRepository.cs

隐藏行号 复制代码 ?
  1. public interface ILocation_CountryRepository
    
  2.     {
    
  3.         IList<Location_Country> FindAll();
    
  4.         IList<Location_Country> FindIndistinct(Country_Query_Index country_Query_Index , object o);
    
  5.         bool Create(Location_Country location_Country);
    
  6.         bool Update(Location_Country location_Country);
    
  7.         bool Delete(Location_Country location_Country);
    
  8.         Location_Country FindOne(Country_Query_Index country_Query_Index, object o);
    
  9.     }
    

  通过QueryOver和Lambda表达式进行数据查询

Location_CountryRepository.cs

隐藏行号 复制代码 ?
  1. public class Location_CountryRepository : ILocation_CountryRepository
    
  2.     {
    
  3.         public Location_CountryRepository()
    
  4.         {
    
  5.         }
    
  6.         public IList<Location_Country> FindAll()
    
  7.         {
    
  8.             using (var session = SessionManager.GetCurrentSession())
    
  9.             {
    
  10.                 var query = session.QueryOver<Location_Country>()
    
  11.                 .OrderBy(p => p.CountryId).Asc
    
  12.                 .List();
    
  13.                 return query;
    
  14.             }
    
  15.         }
    
  16.         //模糊查询
    
  17.         public IList<Location_Country> FindIndistinct(Country_Query_Index country_Query_Index, object o)
    
  18.        {
    
  19.            using (var session = SessionManager.GetCurrentSession())
    
  20.            {
    
  21.                IList<Location_Country> query=null;
    
  22.                switch (country_Query_Index)
    
  23.                {
    
  24.                    case Country_Query_Index.CountryName:
    
  25.                        {
    
  26.                            query = session.QueryOver<Location_Country>()
    
  27.                                .WhereRestrictionOn(k => k.CountryName).IsLike(o)
    
  28.                                .OrderBy(p => p.CountryId).Asc
    
  29.                                .List();
    
  30.                            break;
    
  31.                        }
    
  32.                    case Country_Query_Index.Code1:
    
  33.                        {
    
  34.                            query = session.QueryOver<Location_Country>()
    
  35.                                .WhereRestrictionOn(k => k.CountryCode1).IsLike(o)
    
  36.                                .OrderBy(p => p.CountryId).Asc
    
  37.                                .List();
    
  38.                            break;
    
  39.                        }
    
  40.                    case Country_Query_Index.Code2:
    
  41.                        {
    
  42.                            query = session.QueryOver<Location_Country>()
    
  43.                                .WhereRestrictionOn(k => k.CountryCode2).IsLike(o)
    
  44.                                .OrderBy(p => p.CountryId).Asc
    
  45.                                .List();
    
  46.                            break;
    
  47.                        }
    
  48.                    case Country_Query_Index.DialCode:
    
  49.                        {
    
  50.                            query = session.QueryOver<Location_Country>()
    
  51.                                .WhereRestrictionOn(k => k.CountryDialCode).IsLike(o)
    
  52.                                .OrderBy(p => p.CountryId).Asc
    
  53.                                .List();
    
  54.                            break;
    
  55.                        }
    
  56.                }
    
  57.                return query;
    
  58.            }
    
  59.        }
    
  60.         public Location_Country FindOne(Country_Query_Index country_Query_Index,object o)
    
  61.         {
    
  62.             using (var session = SessionManager.GetCurrentSession())
    
  63.             {
    
  64.                 Location_Country query = null;
    
  65.                switch (country_Query_Index)
    
  66.                {
    
  67.                    case Country_Query_Index.CountryId:
    
  68.                        {
    
  69.                            query = session.QueryOver<Location_Country>()
    
  70.                                .Where(p => p.CountryId==(int)o)
    
  71.                                .SingleOrDefault();
    
  72.                            break;
    
  73.                        }
    
  74.                    case Country_Query_Index.CountryName:
    
  75.                        {
    
  76.                            query = session.QueryOver<Location_Country>()
    
  77.                                .Where(p => p.CountryName == o.ToString())
    
  78.                                .SingleOrDefault();
    
  79.                            break;
    
  80.                        }
    
  81.                    case Country_Query_Index.Code1:
    
  82.                        {
    
  83.                            query = session.QueryOver<Location_Country>()
    
  84.                                .Where(p => p.CountryCode1 == o.ToString())
    
  85.                                .SingleOrDefault();
    
  86.                            break;
    
  87.                        }
    
  88.                    case Country_Query_Index.Code2:
    
  89.                        {
    
  90.                            query = session.QueryOver<Location_Country>()
    
  91.                                .Where(p => p.CountryCode2 == o.ToString())
    
  92.                                .SingleOrDefault();
    
  93.                            break;
    
  94.                        }
    
  95.                    case Country_Query_Index.DialCode:
    
  96.                        {
    
  97.                            query = session.QueryOver<Location_Country>()
    
  98.                                .Where(p => p.CountryDialCode == o.ToString())
    
  99.                                .SingleOrDefault();
    
  100.                            break;
    
  101.                        }
    
  102.                }
    
  103.                return query;
    
  104.            }
    
  105.         }
    
  106.         public bool Create(Location_Country model)
    
  107.         {
    
  108.             bool result = false;
    
  109.             using (var session = SessionManager.GetCurrentSession())
    
  110.             {
    
  111.                 using (var trans = session.BeginTransaction())
    
  112.                 {
    
  113.                     session.Save(model);
    
  114.                     trans.Commit();
    
  115.                     result = true;
    
  116.                 }
    
  117.             }
    
  118.             return result;
    
  119.         }
    
  120.         public bool Update(Location_Country model)
    
  121.         {
    
  122.             bool result = false;
    
  123.             using (var session = SessionManager.GetCurrentSession())
    
  124.             {
    
  125.                 using (var trans = session.BeginTransaction())
    
  126.                 {
    
  127.                     session.Update(model);
    
  128.                     trans.Commit();
    
  129.                     result = true;
    
  130.                 }
    
  131.             }
    
  132.             return result;
    
  133.         }
    
  134.         public bool Delete(Location_Country model)
    
  135.         {
    
  136.             bool result = false;
    
  137.             using (var session = SessionManager.GetCurrentSession())
    
  138.             {
    
  139.                 using (var trans = session.BeginTransaction())
    
  140.                 {
    
  141.                     session.Delete(model);
    
  142.                     trans.Commit();
    
  143.                     result = true;
    
  144.                 }
    
  145.             }
    
  146.             return result;
    
  147.         }
    
  148.     }
    

转载于:https://www.cnblogs.com/leowuang/archive/2011/10/29/2228829.html

NHibernate3.2+Asp.net MVC3+Extjs 4.0.2项目实践(二): NHibernate数据访问层实现相关推荐

  1. petshop4.0 详解之二(数据访问层之数据库访问设计)

    在系列一中,我从整体上分析了PetShop的架构设计,并提及了分层的概念.从本部分开始,我将依次对各层进行代码级的分析,以求获得更加细致而深入的理解.在PetShop 4.0中,由于引入了ASP.Ne ...

  2. Microsoft PetShop 3.0 设计与实现 分析报告―――数据访问层

    Microsoft PetShop 3.0 设计与实现--数据访问层 最近对多层设计实现和.Net产生了兴趣,从而研究了一下比较著名的多层范例程序――PetShop,现在的版本是3.0,和以前的版本从 ...

  3. Scott Mitchell 的ASP.NET 2.0数据教程之一: 创建一个数据访问层

    原文 | 下载本教程中的编码例子 | 下载本教程的英文PDF版 导言 作为web开发人员,我们的生活围绕着数据操作.我们建立数据库来存储数据,写编码来访问和修改数据,设计网页来采集和汇总数据.本文是研 ...

  4. Spring.Net+NHibenate+Asp.Net mvc +ExtJs 系列 3 ----数据访问层

    在上一篇中,我们已经搭建起了整个解决方案的项目,并且建好了数据库,完成了实体类和Nhibernate映射文件.在本文中,将定义数据访问接口,并利用Nhibernate实现接口,利用Spring.net ...

  5. ASP.NET3.5 企业级项目开发 -- 第二章(续) 数据访问层(DAL)的开发解决方案提出...

    ASP.NET3.5 企业级项目开发 -- 第二章(续) 数据访问层(DAL)的开发解决方案提出 前言:首先给大家说声"对不起",因为自从打算写这系列的文章以来,得到大家很多的支持 ...

  6. ASP.NET数据库访问系列教程01-概述篇 创建数据访问层(下)

    ASP.NET数据库访问系列教程 本教程深入探讨了基于ASP.NET 2.0技术的数据库访问方法和模式.这些介绍非常简明,并且提供了一步步的指导和大量的截屏. 该系列教程包括: 概述篇 基础报表 主/ ...

  7. ASP.NET数据库访问系列教程01-概述篇 创建数据访问层(中)

    ASP.NET数据库访问系列教程 本教程深入探讨了基于ASP.NET 2.0技术的数据库访问方法和模式.这些介绍非常简明,并且提供了一步步的指导和大量的截屏. 该系列教程包括: 概述篇 基础报表 主/ ...

  8. PP团队圣经巨著《Application Architecture Guide2.0》14章-数据访问层

    第十四章 数据访问层指导 概览 这一章主要描述设计数据访问层时要注意的主要原则.它们覆盖了设计数据访问层遇到的通常问题及错误.下面的图表展示了数据层怎样嵌入一个通用的应用架构. (cnblog我的图片 ...

  9. ASP.NET3.5 企业级项目开发 -- 第二章 数据访问层(DAL)的开发

    为什么80%的码农都做不了架构师?>>>    ASP.NET3.5 企业级项目开发 -- 第二章 数据访问层(DAL)的开发          前言:本篇主要讲述数据访问层的开发, ...

最新文章

  1. grep及正则表达式
  2. python分割数字_python实现整数拆分,输出拆分序列
  3. @retention注解作用_分分钟带你玩转SpringBoot自定义注解
  4. 光伏发电项目将全面摸底复核
  5. 什么是SAP Graph
  6. javascript删除数组里的对象
  7. 23产品经理需要具备的运营能力
  8. JavaScript算法(实例二)9*9乘法表
  9. C语言课后习题(21)
  10. java iframe主界面_利用iframe实现各个页面跳转
  11. ubuntu内网环境安装zabbix agent
  12. springboot分页展示功能_基于SpringBoot从零构建博客网站 - 分页显示文章列表功能...
  13. Python-基本语法元素
  14. hbase基础操作命令
  15. 010-flutter dart代码后台执行,没有界面的情况下
  16. SV 接口(interface)
  17. 日记--node.js 和nginx对比环境变量立刻生效https://www.cnblogs.com/zht-blog/p/4033951.html
  18. 程序员的岗位路线规划,不止是编程?
  19. 国产开源基于 Java 的轻量级 CMS 解决方案 天梯
  20. 第k大元素(时间复杂度为O(n))

热门文章

  1. 干货 | 有赞数据仓库实践之路
  2. 关于HttpUtility.UrlEncode,HttpUtility.UrlDecode,Server.UrlEncode,Server.UrlDecode
  3. c语言随机抽取小程序_C语言整人小程序,慎用,谨记!
  4. 【Tensorflow】Tensorflow 自定义梯度
  5. Ubuntu16.04 sudo apt-get install lib***-dev安装失败,无法锁定文件,sudo apt-get update 更新失败也无法解决
  6. css默认的font-size是什么意思,常用的css属性:font-size等
  7. 如何制作一个类似Tiny Wings的游戏 Cocos2d-x 2 1 4
  8. Maven核心概念及Eclipse使用Maven
  9. NLP(新闻文本分类)——数据读取与数据分析
  10. 贪心法——最优装载问题