欢迎访问我的个人博客:三秋邦

微积微发之NHibernate系列之NHibernate的配置

我们先建一个项目,如下图如示:

整个web.config配置信息如下:

<?xml version="1.0"?>
<configuration>

  <configSections>
    <!--声明我们要添加一个配置节点hibernate-configuration-->
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate"/>
    <!--声明我们要添加一个配置节点hibernate-configuration-->

    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <!--在这里定义我们的配置节点信息-->
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.connection_string">
        Server=.;Initial Catalog=MyTest;Integrated Security=SSPI;
      </property>
      <mapping assembly="NHibernateTest"/>
    </session-factory>
  </hibernate-configuration>
  <!--在这里定义我们的配置节点信息-->
  <appSettings />
  <connectionStrings />
  <system.web>
    <compilation debug="true">

      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>

    </compilation>
    <!--
            通过 <authentication> 节可以配置
            安全身份验证模式,ASP.NET 
            使用该模式来识别来访用户身份。 
        -->
    <authentication mode="Windows" />
    <!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 <customErrors> 节
            可以配置相应的处理步骤。具体而言,
            开发人员通过该节可配置要显示的 html 错误页,
            以代替错误堆栈跟踪。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->

    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </controls>
    </pages>

    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>

  </system.web>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
                type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>

  <!-- 
        system.webServer 节是在 Internet Information Services 7.0 下运行 ASP.NET AJAX
        所必需的。对早期版本的 IIS 来说则不需要此节。
    -->
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ScriptModule" />
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <remove name="ScriptHandlerFactory" />
      <remove name="ScriptHandlerFactoryAppServices" />
      <remove name="ScriptResource" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
           type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
           type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

</configuration>

可以到下载NHibernate:http://sourceforge.net/projects/nhibernate/files/NHibernate/

下载下来后在项目中添加如下的引用:

 

 

 

然后使用动软件代码生成器生成数据库中一个表对应的类和映射关系两个文件:

然后选择要生成的表,以及跟据那个模板生成:

然后选择导出,导出后会在选择的输出目录产生如下图的文件:

然后我在项目新建两个文件,分别用来保存Entity(实体类,即通过映射关系文件对应数据库中的张表)和XmlMapping(映射关系文件)里的文件(当然你也可以在这个解决方案里再建一个类库用来存放这些生成文件):

由于数据库的users表的命名不规范,开头字母应该大写,所以我把Entity文件夹里的users.cs改成了Users.cs,里面代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

//Nhibernate Code Generation Template 1.0
//author:MythXin
//blog:www.cnblogs.com/MythXin
//Entity Code Generation Template
namespace NHibernateTest.Entity  
{//这个命名空间本来生成是Maticsoft.Entity,我把改成NHibernateTest.Entity,
    //这样我一看就知道它是在我的NHibernateTest程序集下的Entity文件下
    public class Users
    {
        /// <summary>
        /// id
        /// </summary>
        public virtual int id
        {
            get;
            set;
        }
        /// <summary>
        /// username
        /// </summary>
        public virtual string username
        {
            get;
            set;
        }
        /// <summary>
        /// password
        /// </summary>
        public virtual string password
        {
            get;
            set;
        }
    }
}

这个映射关系的XML文件我也改成Users.hbm.xml的名字了,这里要特别提醒各位右击这个文件,选中属性把“生成操作”里的选项改成“嵌入的资源”,为了符合一般的文件命名规范,代码如下:

<?xml version="1.0"  encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateTest" namespace="NHibernateTest.Entity">
  <!--assembly="NHibernateTest"意思是你的Users.cs文件是放在哪个程序集里面。namespace="NHibernateTest.Entity"这个就是指明他的命名空间-->
    <class name="NHibernateTest.Entity.Users,NHibernateTest" table="users">
    <!--<class name="NHibernateTest.Entity.User,NHibernateTest" table="users">这行的name属性的属性值中的"NHibernateTest.Entity.User"指明你要映射的类的完整命名空间,",NHibernateTest"这里指明它是在那个程序集下,table属性指明被映射的表名-->
        <id name="id" column="id" type="int" unsaved-value="0">
                  <generator class="native" />                   
          </id>              
        <property name="username" column="username" type="string"  />
        <property name="password" column="password" type="string"  />
                
    </class>
</hibernate-mapping>

 要查看你的Users类的程序集叫什么,可右击它所在的项目,选择属性如下图所示:

 

如果你的(Users.cs这样的实体类是放在一个类库里,那你就右击类库选择"属性",即可看到程序集名称叫什么的。

下面我来添加一个NHibernateHelper类,项目列表如下:

 

 NHibernateHelper.cs里的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//请记得引用如下两个命名空间
using NHibernate;
using NHibernate.Cfg;
namespace NHibernateTest
{
    public sealed class NHibernateHelper
    {
        private const String CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory sessionFactory;
        static NHibernateHelper()
        {
            sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }
        public static ISession GetCurrentSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                currentSession = sessionFactory.OpenSession();
                context.Items[CurrentSessionKey] = currentSession;
            }
            return currentSession;
        }

        public static void CloseSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                //No current session
                return;
            }
            currentSession.Close();
            context.Items.Remove(CurrentSessionKey);
        }
        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}

然后我们在一个页面的后台文件写下如下代码,即可在数据库中保存数据了,简单吧!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//请记得添加如下两个命名空间
using NHibernate;
using NHibernateTest.Entity;

namespace NHibernateTest
{
    public partial class _Default : System.Web.UI.Page
    {
        ISession session = NHibernateHelper.GetCurrentSession();
        protected void Page_Load(object sender, EventArgs e)
        {
            ITransaction transaction = session.BeginTransaction();
            Users users = new Users();
            users.username = "钓鱼岛是中国的,日本也是中国的。";
            users.password = "钓鱼岛是中国的,日本也是中国的。";
            session.Save(users);
            transaction.Commit();
            NHibernateHelper.CloseSession();
        }
    }
}

里面的东西下篇再讲吧!这篇的主要目地是配置出来,先下效果,然后下一篇我们再来讲那些是什么意思吧!忘了早餐还没吃呢?又到该吃中餐的时候了。追夢,你妈叫回家吃饭咯!                          来咯!!!

posted @ 2012-09-01 13:16  追夢  阅读(1333)  评论(0编辑  收藏  举报
欢迎访问我的个人博客:三秋邦