本篇目的:配置Spring.Net和Nhibernate。配置Spring.Net來注入Nhibernate需要的SessionFactory,配置業務邏輯層所需要的Dao層屬性的支援。配置這套架構與web程式關聯。
在上一篇我們已經将三層基本搭建起來了。這篇中我們将要講述怎樣通過配置,将三層通過IOC注入。現在我們開始我們的旅程:
第一步:配置實體類【Model】對應的資料庫映射檔案。Nhibernate中要求映射檔案必須按照約定的檔案命名格式進行命名。至于放到什麼項目中都可以,為了便于了解,我們把資料庫表和實體類映射檔案放到Model項目中。并建立一個專門的檔案夾Mappings來存放映射檔案。添加實體類映射資料庫檔案User.hbm.xml。映射檔案命名格式:類名.hbm.xml其實就是一個xml檔案。下圖是項目中的截圖:

User.hbm.xml檔案代碼:
代碼
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="MyWeb.WebTemp.Model.User,MyWeb.WebTemp.Model" table="Hksj_User" lazy="false">
<id name="Id" column="Id" type="Int32">
<generator class="native" />
</id>
<property name="Name" column="SName" type="String" length="20" />
<property name="NickName" column="SNickName" type="String" length="20" />
<property name="PassWord" column="SPassWord" type="String" length="30" />
<property name="IdentifyId" column="SIdentifyId" type="String" length="30" />
<property name="Phone" column="SPhone" type="String" length="50" />
<property name="Email" column="SEmail" type="String" length="50" />
<property name="CreateTime" column="DCreateDate" type="DateTime" />
<property name="Creator" column="SCreator" type="String" length="20" />
<property name="LastTimeLogOn" column="DLastTimeLogOn" type="DateTime" />
</class>
</hibernate-mapping>
注意:在User.hbm.xml檔案上 右擊-->的屬性 将[生成操作] 設定為嵌入資源
對于這部分簡單說一下,這是我們為Nhibernate操作資料庫做鋪墊。Nhibernate就是這樣要求的。我們按照模闆來配置就行了。User.hbm.xml中的配置是根據資料庫中的表和我們的實體類User進行對應的。這方面不多講,可以參考Nhibernate的官方文檔。不難,認真看,就能猜出大部分。例如:<property name="Email" column="SEmail" type="String" length="50" /> 意思: property name指的是:User類的屬性名字 Email對應資料庫的列SEmail 類型是String,長度50個字元。
第二步:配置webconfig!這一步非常關鍵也很重要。但是基本上就是模闆,大家拷貝一下就行了。沒什麼好說的,注釋也很詳細。大家看一下,就在幾個地方添加就行了。
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<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>
<!--Spring.Net For Log4net -->
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
<section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
<section name="SpringOverrideProperty" type="System.Configuration.NameValueSectionHandler"/>
<!--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
</configSections>
<SpringOverrideProperty>
<add key="NamingStrategy.TableHead" value=""/>
<add key="db.datasource" value="server=.;uid=sa;pwd=123;database=HkTemp;"/>
<!-- 0 to 6 (1 Debug 4 Error)-->
<add key="SystemInit.IsDebug" value="true"/>
<add key="SystemInit.Level" value="4"/>
<add key="MappingAssemblies" value="Hksj.HkWeb.HibernateDao,Hksj.HkWeb.HibernateDao"/>
</SpringOverrideProperty>
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="Logs\Application.log.txt"/>
<param name="datePattern" value="MM-dd HH:mm"/>
<param name="AppendToFile" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender">
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Logs/Log.txt"/>
<param name="MaxSizeRollBackups" value="10"/>
<param name="MaximumFileSize" value="100K"/>
<param name="RollingStyle" value="Size"/>
<param name="StaticLogFileName" value="true"/>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
<spring>
<parsers>
<parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/>
<parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
</parsers>
<context>
<resource uri="~/Configs/CommonDao.xml"/>
<resource uri="~/Configs/HibernateDaos.xml"/>
<resource uri="~/Configs/Services.xml"/>
<!--<resource uri="~/Configs/Webs.xml"/>-->
<resource uri="~/Configs/Controls.xml"/>
</context>
<!--<objects xmlns="http://www.springframework.net"/>-->
</spring>
<appSettings>
</appSettings>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
<compilation debug="true">
<assemblies>
<add assembly="System.Core, 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.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/"/>
</providers>
</membership>
<profile>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/"/>
</profile>
<roleManager enabled="false">
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</roleManager>
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<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>
<namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
</namespaces>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<!--+++++++++++++++++++++++++spring.net nhibernate++++++++++++++++++++++++-->
<add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
<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"/>
<add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate12"/>
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
</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>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="OptionInfer" value="true"/>
</compilers>
</system.codedom>
<system.web.extensions/>
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ScriptModule"/>
<remove name="UrlRoutingModule"/>
<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"/>
<remove name="MvcHttpHandler"/>
<remove name="UrlRoutingHandler"/>
<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"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
</system.webServer>
</configuration>
注意:
1、其中這個設定要和你的Nhibernate版本一緻。我用的版本比較老。這個一定注意。<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
2、 下面這段的意思是我們在這個地方引入:web網站項目 Configs檔案夾下的CommonDao.xml....這幾個檔案。待會将這幾個檔案的代碼貼出來。
<context>
<resource uri="~/Configs/CommonDao.xml"/> ---用于配置NhibernateSessionFactory,資料庫連接配接等【Nhib核心配置】
<resource uri="~/Configs/HibernateDaos.xml"/>-----配置Dao層所需要的SessionFactory
<resource uri="~/Configs/Services.xml"/> -----配置業務邏輯層所需要的Dao層的支援
<resource uri="~/Configs/Controls.xml"/> -----目前此檔案用于Controls的配置注入,暫時不考慮
</context>
3、一一展示在Web網站項目下
我們在web項目根目錄下建立檔案Configs。并在Configs中添加以上四個xml檔案。下面我一一講述他們的作用。
先看一下目前項目的截圖:
(1)CommonDao.xml檔案是Nhibernate操作資料庫的核心的配置。并配置了可注入到Dao層的SessionFactory。沒什麼好說的,其實也都是模闆。代碼如下:
<objects xmlns="http://www.springframework.net"
xmlns:db="http://www.springframework.net/database">
<description>
Definitions for the NHibernate Objects.
</description>
<!-- Database and NHibernate Configuration這下面是配置使用Nhibernate -->
<db:provider id="DbProvider"
provider="SqlServer-2.0"
connectionString="database=HkTemp;uid=sa;pwd=123;server=.;"/>
<object id="SessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate12">
<property name="DbProvider" ref="DbProvider" />
<property name="MappingAssemblies">
<list>
<!--這是配置嵌入資源的xx類對應的xx.hbm.xml檔案所在的項目名稱-->
<value>MyWeb.WebTemp.Model</value>
</list>
</property>
<property name="HibernateProperties">
<dictionary>
<entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<entry key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<entry key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<entry key="show_sql" value="true" />
</dictionary>
</object>
<object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate12">
<property name="sessionFactory" ref="SessionFactory" />
<object id="TransactionInterceptor" type="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data">
<property name="TransactionManager" ref="HibernateTransactionManager" />
<property name="TransactionAttributeSource">
<object type="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data" />
</objects>
注:上面代碼中有兩個地方需要看一下對應你的項目改一下。一個就是連接配接字元串。我不用說了。另外一個就是:實體類映射資料庫檔案hbm.xml檔案所在的項目名稱一定要配置對了。
(2)HibernateDaos.xml用于配置Dao層的xml檔案。這個可以放到CommonDao中,如果系統比較複雜的話,最好單獨拿出來放到一個xml檔案中,這樣比較清晰。還是看代碼如下:
<objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database">
<object id="UserDao" type="Hksj.HkWeb.HibernateDao.Hibernate.UserDaoHibernate,Hksj.HkWeb.HibernateDao">
<property name="SessionFactory" ref="SessionFactory" />
注:type="MyWeb.WebTemp.HibernateDao.UserDaoHibernate,MyWeb.WebTemp.HibernateDao">
加粗的是Dao層實作類的全名稱。後面那個是對應的項目名稱【其實是程式集】。看到了我們Dao層配置了SessionFactory。呵呵這裡不詳細講。為什麼Dao層裡面沒有屬性SessionFactory,但是我們這裡配置了呢?呵呵
(3)Services.xml是配置我們的業務邏輯實作類的。看代碼:
<object id="UserService" type="MyWeb.WebTemp.BLL.UserServiceImpl,MyWeb.WebTemp.BLL">
<property name="UserDao" ref="UserDao" />
這段代碼就是将我們的Dao實體注入給業務邏輯層
到此為止,我們把Spring.Net和Nhibernate的配置基本就搞定了。
這塊的配置是夠複雜的。不過親自配置一遍後,熟悉了就沒什麼的了。
這裡要對web項目添加Model項目引用,BLL層項目引用。還有Dao層項目引用。添加spring.net和Nhibernate的dll的引用。
先寫到這。。。
文章索引:
<a href="http://www.cnblogs.com/fly_dragon/archive/2010/09/06/1819422.html">搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 架構 (一)</a>
<a href="http://www.cnblogs.com/fly_dragon/archive/2010/09/06/1819494.html">搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 架構 (二)建立你的項目</a>
<a href="http://www.cnblogs.com/fly_dragon/archive/2010/09/06/1819547.html">搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 架構 (三)實作資料庫接口層和業務邏輯層</a>
<a href="http://www.cnblogs.com/fly_dragon/archive/2010/09/archive/2010/09/07/1820301.html">搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 架構 (四)配置全攻略</a>
<a href="../archive/2010/09/07/1820449.html">搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 架構 (五)測試你的成果</a>
<a href="../archive/2010/09/07/1820472.html">搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 架構 (六)寫在後面的話</a>