本篇目的:配置Spring.Net和Nhibernate。配置Spring.Net来注入Nhibernate需要的SessionFactory,配置业务逻辑层所需要的Dao层属性的支持。配置这套框架与web程序关联。
在上一篇我们已经将三层基本搭建起来了。这篇中我们将要讲述怎样通过配置,将三层通过IOC注入。现在我们开始我们的旅程:
第一步:配置实体类【Model】对应的数据库映射文件。Nhibernate中要求映射文件必须按照约定的文件命名格式进行命名。至于放到什么项目中都可以,为了便于理解,我们把数据库表和实体类映射文件放到Model项目中。并建立一个专门的文件夹Mappings来存放映射文件。添加实体类映射数据库文件User.hbm.xml。映射文件命名格式:类名.hbm.xml其实就是一个xml文件。下图是项目中的截图:
User.hbm.xml文件代码:
<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!这一步非常关键也很重要。但是基本上就是模板,大家拷贝一下就行了。没什么好说的,注释也很详细。大家看一下,就在几个地方添加就行了。
<!--
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>
</sectionGroup>
</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>
<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"/>
</sectionGroup>
<section name="SpringOverrideProperty" type="System.Configuration.NameValueSectionHandler"/>
<!--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
</configSections>
<!--Spring.Net For Log4net -->
<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">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Logs/Log.txt"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="10"/>
<param name="MaximumFileSize" value="100K"/>
<param name="RollingStyle" value="Size"/>
<param name="StaticLogFileName" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
</layout>
</appender>
<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>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<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"/>
</providers>
</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"/>
<!--+++++++++++++++++++++++++spring.net nhibernate++++++++++++++++++++++++-->
<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"/>
<!--+++++++++++++++++++++++++spring.net nhibernate++++++++++++++++++++++++-->
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate12"/>
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
<!--+++++++++++++++++++++++++spring.net nhibernate++++++++++++++++++++++++-->
</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="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</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"/>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, 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>
</property>
</object>
<object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate12">
<property name="DbProvider" ref="DbProvider" />
<property name="sessionFactory" ref="SessionFactory" />
</object>
<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" />
</property>
</object>
</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" />
</object>
</objects>
注:type="MyWeb.WebTemp.HibernateDao.UserDaoHibernate,MyWeb.WebTemp.HibernateDao">
加粗的是Dao层实现类的全名称。后面那个是对应的项目名称【其实是程序集】。看到了我们Dao层配置了SessionFactory。呵呵这里不详细讲。为什么Dao层里面没有属性SessionFactory,但是我们这里配置了呢?呵呵
(3)Services.xml是配置我们的业务逻辑实现类的。看代码:
<objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database">
<object id="UserService" type="MyWeb.WebTemp.BLL.UserServiceImpl,MyWeb.WebTemp.BLL">
<property name="UserDao" ref="UserDao" />
</object>
</objects>
这段代码就是将我们的Dao实体注入给业务逻辑层
到此为止,我们把Spring.Net和Nhibernate的配置基本就搞定了。
这块的配置是够复杂的。不过亲自配置一遍后,熟悉了就没什么的了。
这里要对web项目添加Model项目引用,BLL层项目引用。还有Dao层项目引用。添加spring.net和Nhibernate的dll的引用。
先写到这。。。
文章索引:
搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 框架 (一)
搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 框架 (二)创建你的项目
搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 框架 (三)实现数据库接口层和业务逻辑层
搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 框架 (四)配置全攻略