Spring.Net + NHibernate 入门例子

Spring.Net 是一个很强大的框架,在java里非常的火,NHibernate也是从java里移植过来的.不过和Java下面的用法有所区别.下面我们以一个实例来说说他们在.net下的用法.
新建一个项目:名字叫SpringHiberate.
首先,我们修改我们的配置文件web.config:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
    </sectionGroup>
    <section name="SpringOverrideProperty" type="System.Configuration.NameValueSectionHandler"/>
    <section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <SpringOverrideProperty>
    <add key="DbProvider.ConnectionString" value="Data Source=192.168.1.21;Database=FastSpring20;User ID=sa;Password=oilchem2007;Trusted_Connection=False"/>
    <add key="SystemInit.IsDebug" value="true"/>
    <add key="SystemInit.Level" value="4"/>
  </SpringOverrideProperty>
 

  <!-- Spirng.Net 配置 -->
  <spring>
    <context>
      <resource uri="config://spring/objects"/>
      <resource uri="assembly://SpringHiberate/SpringHiberate/spring_bean_dao.xml"/>
    </context>

 <objects xmlns="http://www.springframework.net"/>
  </spring>
 
  <appSettings/>

  <connectionStrings/>

  <system.web>
    <compilation debug="true" />
    <authentication mode="Windows" />
   
    <httpModules>
      <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
    </httpModules>
   
    <httpHandlers>
      <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
    </httpHandlers>
  </system.web>
</configuration>

然后我们添加一个Model类User.cs:

 1using System;
 2
 3namespace SpringHiberate.dao.model
 4{

  public class User
 6    {
 7        private Int32 id;
 8
 9        public Int32 Id
10        {
11            get { return id; }
12            set { id = value; }
13        }
14        private string name;
15
16        public string Name
17        {
18            get { return name; }
19            set { name = value; }
20        }
21        private string email;
22
23        public string Email
24        {
         get { return email; }
26            set { email = value; }
27        }
28    }
29}我们再在User.cs目录里添加一个文件User.hbm.xml,文件的生成操作为嵌入的资源

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="SpringHiberate.dao.model.User,SpringHiberate" table="FS_User" lazy="false">
    <id name="Id" column="id" type="Int32">
      <generator class="native" />
    </id>
    <property name="Name" column="uname" type="String" length="50" />
    <property name="Email" column="uemail" type="String" length="50" />
</hibernate-mapping>然后我们写一个SQLProvider类SQLProvider.cs.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Spring.Data.Common;

namespace SpringHiberate.dao
{
    public class SQLProvider : IDbProvider
    {
        #region IDbProvider 成员
        private string _connectionString = "";
        public string ConnectionString
        {
            get
            {
                return this._connectionString;
            }
            set
            {
                this._connectionString = value;
            }
        }

        public IDbCommand CreateCommand()
        {
            return null;
        }

        public object CreateCommandBuilder()
        {
            return null;
        }

        public IDbConnection CreateConnection()
        {
            return null;
        }

        public IDbDataAdapter CreateDataAdapter()
        {
            return null;
        }

        public IDbDataParameter CreateParameter()
        {
            return null;
        }

        public string CreateParameterName(string name)
        {
            return null;
        }

        public string CreateParameterNameForCollection(string name)
        {
            returnpublic IDbMetadata DbMetadata
        {
            get {
                return null;
            }
        }

        public string ExtractError(Exception e)
        {
            return null;
        }

        public bool IsDataAccessException(Exception e)
        {
            return false;
        }

        #endregion
    }
}
在写一个UserDao类(UserDao.cs)来操作
using System;
using System.Collections;
using Spring.Data.NHibernate.Support;
using SpringHiberate.dao.model;

namespace SpringHiberate.dao
{
    public class UserDao : HibernateDaoSupport
    {
        public void Save(User user)
        {
            HibernateTemplate.Save(user);
        }

        public void Delete(User user)
        {
            HibernateTemplate.Delete(user);
        }

        public void Update(User user)
        {
            HibernateTemplate.Update(user);
        }

        public IList FindAll()
        {
            return HibernateTemplate.LoadAll(typeof(User));
        }

        public User Find(Object ID)
        {
            return (User)HibernateTemplate.Load(typeof(User), ID);
        }
    }
}
现在代码部分基本写完,我们开始写spring的配置文件(spring_bean_dao.xml),文件的生成操作也为嵌入的资源,他配置了数据库操作以及DAO部分,页面的操作DAO也是依赖注入的


<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
<object id="DbProvider" type="SpringHiberate.dao.SQLProvider, SpringHiberate">
    <property name="ConnectionString" value="Data Source=192.168.1.21;Database=FastSpring20;User ID=sa;Password=oilchem2007;Trusted_Connection=False" />
  </object>

  <object id="SessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate12">
    <property name="DbProvider" ref="DbProvider" />
    <property name="MappingAssemblies">
      <list>
        <value>SpringHiberate</value>
      </list>
    </property>
    <property name="HibernateProperties">
      <dictionary>
        <entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
        <entry key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
        <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>
object id="UserDao" type="SpringHiberate.dao.UserDao">
    <property name="SessionFactory" ref="SessionFactory" />
  </object>

  <object type="~/Default.aspx">
    <property name="UserDao" ref="UserDao" />
  </object>
</objects>修改Default.aspx.cs文件里的内容:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SpringHiberate.spring;
using SpringHiberate.dao;

namespace SpringHiberate
{
    public partial class _Default : System.Web.UI.Page
    {
        private UserDao userDao;

        public UserDao UserDao
        {
            get { return userDao; }
            set { userDao = value; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(hello.Name);
            SpringHiberate.dao.model.User u = new SpringHiberate.dao.model.User();
            u.Name = "safa";
            u.Email = "eicesoft@126.com";
            userDao.Save(u);
        }
    }
}
好了,完成了.很简单吧.下面运行一下,然后看看数据库是不是新建了一条数据.
Spring.Net简化了数据框架NHibernate的操作.对页面进行注入,实现了松耦合.
Spring.Net远远不止这些.其他的方面在以后的文章中继续介绍

阅读更多
想对作者说点什么? 我来说一句

基于winform的spring.net+Nhibernate示例

2012年07月17日 4.58MB 下载

NHibernate + spring.net 整合例子

2009年06月26日 4.39MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭