Spring.Net&NHibernate 学习 5

原创 2007年09月13日 15:42:00
创建数据库:NHibernate
创建表:my_users
CREATE TABLE [dbo].[my_users] (
    [LogonId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
    [UserName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [Password] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [EmailAddress] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [LastLogon] [datetime] NULL
    ) ON [PRIMARY]
    GO
    ALTER TABLE [dbo].[my_users] ADD
    CONSTRAINT [PK_my_users] PRIMARY KEY  CLUSTERED
    (
    [LogonId]
    )  ON [PRIMARY]
    GO

创建项目:SpringAndNHibernate
修改默认命名空间为:Spring.NHibernate
新建实体类:my_users.cs

using System;
using System.Collections;
using System.Web.UI.WebControls;

namespace Spring.NHibernate
{
    #region Myuser

    /// <summary>
    /// Myuser object for NHibernate mapped table 'my_users'.
    /// </summary>
    public class Myuser : System.IComparable
        {
        #region Member Variables
       
        protected string _id;
        protected string _userName;
        protected string _password;
        protected string _emailAddress;
        protected DateTime _lastLogon;
        protected static String _sortExpression = "Id";
        protected static SortDirection _sortDirection = SortDirection.Ascending;

        #endregion

        #region Constructors

        public Myuser() { }

        public Myuser( string userName, string password, string emailAddress, DateTime lastLogon )
        {
            this._userName = userName;
            this._password = password;
            this._emailAddress = emailAddress;
            this._lastLogon = lastLogon;
        }

        #endregion

        #region Public Properties

        public virtual string Id
        {
            get {return _id;}
            set
            {
                if ( value != null && value.Length > 50)
                    throw new ArgumentOutOfRangeException("Invalid value for Id", value, value.ToString());
                _id = value;
            }
        }

        public virtual string UserName
        {
            get { return _userName; }
            set
            {
                if ( value != null && value.Length > 50)
                    throw new ArgumentOutOfRangeException("Invalid value for UserName", value, value.ToString());
                _userName = value;
            }
        }

        public virtual string Password
        {
            get { return _password; }
            set
            {
                if ( value != null && value.Length > 50)
                    throw new ArgumentOutOfRangeException("Invalid value for Password", value, value.ToString());
                _password = value;
            }
        }

        public virtual string EmailAddress
        {
            get { return _emailAddress; }
            set
            {
                if ( value != null && value.Length > 50)
                    throw new ArgumentOutOfRangeException("Invalid value for EmailAddress", value, value.ToString());
                _emailAddress = value;
            }
        }

        public virtual DateTime LastLogon
        {
            get { return _lastLogon; }
            set { _lastLogon = value; }
        }

        public static String SortExpression
        {
            get { return _sortExpression; }
            set { _sortExpression = value; }
        }

        public static SortDirection SortDirection
        {
            get { return _sortDirection; }
            set { _sortDirection = value; }
        }
        #endregion
       
        #region IComparable Methods
        public int CompareTo(object obj)
        {
            if (!(obj is Myuser))
                throw new InvalidCastException("This object is not of type Myuser");
           
            int relativeValue;
            switch (SortExpression)
            {
                case "Id":
                    relativeValue = this.Id.CompareTo(((Myuser)obj).Id);
                    break;
                case "UserName":
                    relativeValue = (this.UserName != null) ? this.UserName.CompareTo(((Myuser)obj).UserName) : -1;
                    break;
                case "Password":
                    relativeValue = (this.Password != null) ? this.Password.CompareTo(((Myuser)obj).Password) : -1;
                    break;
                case "EmailAddress":
                    relativeValue = (this.EmailAddress != null) ? this.EmailAddress.CompareTo(((Myuser)obj).EmailAddress) : -1;
                    break;
                case "LastLogon":
                    relativeValue = (this.LastLogon != null) ? this.LastLogon.CompareTo(((Myuser)obj).LastLogon) : -1;
                    break;
                default:
                    goto case "Id";
            }
            if (Myuser.SortDirection == SortDirection.Ascending)
                relativeValue *= -1;
            return relativeValue;
        }
        #endregion
    }

    #endregion
}

 实体类映射文件:my_users.hbm.xml (lazy设为false,否则load方法出错)
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="Spring.NHibernate.Myuser, SpringAndNHibernate" table="my_users" lazy="false">
        <id name="Id" type="String" unsaved-value="null">
            <column name="LogonId" length="50" sql-type="varchar" not-null="true" unique="true" index="PK_my_users"/>
            <generator class="native" />
        </id>
        <property name="UserName" type="String">
            <column name="UserName" length="50" sql-type="varchar" not-null="false"/>
        </property>
        <property name="Password" type="String">
            <column name="Password" length="50" sql-type="varchar" not-null="false"/>
        </property>
        <property name="EmailAddress" type="String">
            <column name="EmailAddress" length="50" sql-type="varchar" not-null="false"/>
        </property>
        <property name="LastLogon" type="DateTime">
            <column name="LastLogon" length="8" sql-type="datetime" not-null="false"/>
        </property>
    </class>
</hibernate-mapping>

新建:HelloTest.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace Spring.NHibernate
{
    class HelloTest
    {
       private  string str;
        public void Test()
        {
            Console.Write(str);
            Console.ReadLine();
        }
    }
}

新建:
Spring_bean.xml
<?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
        F:/Spring.Net/spring-objects.xsd">
  <object id="Hello" type="Spring.NHibernate.HelloTest,SpringAndNHibernate">
    <property name="str" value="Hello!"/>
  </object>
</objects>

新建:Spring_nhibernate.xml
<?xml version="1.0" encoding="utf-8" ?>

<objects xmlns='http://www.springframework.net'>



  <!-- NHibernate初始化的 -->

  <object id="DbProvider" type="Spring.NHibernate.SQLProvider,SpringAndNHibernate">

    <property name="ConnectionString" value="Data Source=.;Database=NHibernate;User ID=sa;Password=sa;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>SpringAndNhibernate</value>

      </list>

    </property>

    <property name="HibernateProperties">

      <dictionary>

        <entry

key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>

        <!--entry

key="hibernate.connection.connection_string" value="Data Source=.;Database=NHibernate;User ID=sa;Password=sa;Trusted_Connection=False"/-->

        <entry key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>

        <entry

key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>

      </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="Spring.NHibernate.UserDao, SpringAndNHibernate">

    <property name="SessionFactory" ref="SessionFactory"/>

  </object>

</objects>


新建:SpringContext.cs
using System;
using System.Collections.Generic;
using System.Text;
using Spring.Core;
using Spring.Context;
using Spring.Context.Support;


namespace Spring.NHibernate
{
    class SpringContext
    {
        private static bool isInit = false;

        private static IApplicationContext context;

        public static void init()
        {
            string[] xmlFiles = new string[2];

            xmlFiles[0] = "assembly://SpringAndNHibernate/Spring.NHibernate/Spring_bean.xml";
            xmlFiles[1] = "assembly://SpringAndNHibernate/Spring.NHibernate/Spring_nhibernate.xml";

            context = new XmlApplicationContext(xmlFiles);
            //context = ContextRegistry.GetContext();

            isInit = true;

        }
        public static IApplicationContext Context
        {
            get
            {
                if (!isInit)
                {

                    init();
                }
                return context;
            }

        }
    }
}

新建:SQLProvider.cs
using System;
using System.Collections.Generic;
using System.Text;
using Spring.Data.Common;

namespace Spring.NHibernate
{
    public class SQLProvider:IDbProvider
    {
        public SQLProvider()
        { }

        public System.Data.IDbConnection CreateConnection()
        {
            return null;
        }
        public string CreateParameterName(string name)
        {
            return null;
        }
        public System.Data.IDbDataParameter CreateParameter()
        {
            return null;
        }
        private string connectionString = "";

        public string ConnectionString
        {
            get { return connectionString; }
            set { connectionString = value; }
        }
        public string ExtractError(Exception e)
        {
            return null;
        }
        public System.Data.IDbDataAdapter CreateDataAdapter()
        {
            return null;
        }

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

        public System.Data.IDbCommand CreateCommand()
        {
            return null;
        }

        public object CreateCommandBuilder()
        {
            return null;
        }

        public IDbMetadata DbMetadata
        {

            get
            {
                return null;
            }

        }
    }
}

新建:UserDao.cs
using System;
using System.Collections.Generic;
using System.Text;
using Spring.Data.NHibernate.Support;
using System.Collections;

namespace Spring.NHibernate
{
    public class UserDao:HibernateDaoSupport
    {
        public UserDao()
        { }

        public bool SaveObject(Myuser user)
        {
            HibernateTemplate.Save(user,user.Id);
            return true;
        }
        public bool DeleteObject(Myuser user)
        {
            HibernateTemplate.Delete(user);
            return true;
        }
        public bool UpdateObject(Myuser user)
        {
            HibernateTemplate.Update(user);
            return true;
        }
        public IList GetAllObjectsList()
        {
            return HibernateTemplate.LoadAll(typeof(Myuser));
        }
        public Myuser Load(string ID)
        {
            return (Myuser)HibernateTemplate.Load(typeof(Myuser),ID);
        }
    }
}

新建测试类:StartMain.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Spring.NHibernate;

namespace Spring.NHibernate
{
    public class StartMain
    {
        public StartMain()
        { }

        static void Main()
        {
            SpringContext.init();
            HelloTest test = (HelloTest)SpringContext.Context.GetObject("Hello");
            test.Test();

            UserDao dao = SpringContext.Context.GetObject("UserDao") as UserDao;
            Myuser newUser = null;
            try
            {
                newUser = dao.Load("joe_cool");
            }
            catch
            { }
            if (newUser == null)
            {
                newUser = new Myuser();

                newUser.Id = "joe_cool";

                newUser.UserName = "Joseph Cool";

                newUser.Password = "abc123";

                newUser.EmailAddress = "joe@cool.com";

                newUser.LastLogon = DateTime.Now;
                dao.SaveObject(newUser);
            }
            string str = newUser.LastLogon.ToString();
            Myuser joeCool = dao.Load("joe_cool");
            joeCool.LastLogon = DateTime.Now;
            dao.UpdateObject(joeCool);
            IList recentUsers = dao.GetAllObjectsList();
            foreach (Myuser user in recentUsers)
            {
                Console.WriteLine(user.UserName);
                Console.WriteLine(user.Password);
            }
            Console.ReadLine();
        }
    }
}

运行:Hello!
换行:数据插入数据库
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Spring.NET学习笔记18——整合NHibernate(基础篇)

NHibernate是一个基于.Net的针对关系型数据库的对象持久化(ORM)类库。NHibernate来源于非常优秀的基于Java的NHibernate关系型持久化工具。从数据库底NHibernat...

Spring.NET学习笔记19——整合NHibernate和ASP.NET MVC(基础篇)

ASP.NET MVC Framework是微软官方提供的MVC模式编写ASP.NET Web应用程序的一个框架。MVC(Model-View-Controller)用于表示一种软件架构模式.它把软件...

『Spring.NET+NHibernate+泛型』框架搭建之WebUI(五)★

前面的章节讲解了搭建Model、DAO、BLL,完成了前面这三大块框架的搭建,基本上我们开发一个项目只剩下,也只需要写写WebUI层就行了。

『Spring.NET+NHibernate+泛型』框架搭建之BLL(四)

本节讲解业务逻辑层BLL。很简单和DAO层类似,通过泛型封装相似的功能到父类,其他子类继承父类即可,具体看下面操作。

『Spring.NET+NHibernate+泛型』框架搭建之Model(二)

按照搭建项目的顺序来比较好描述一些,我一般先搭建实体层,本节内容纯属于NHibernate范畴。先上图和代码,然后对着图和代码逐一讲解

『Spring.NET+NHibernate+泛型』框架搭建之DAO(三)★

本节内容介绍Nhibernate所封装的数据库访问层。不过我加入了泛型进行封装。大概思路:首先,我们有一个接口层,还有一个对应的实现层;在接口层中我们先定义一个父接口,父接口中定义每一个接口都可能会用...

使Spring.NET 1.3.2支持NHibernate 3.2 ByCode方式的映射

Spring.NET IoC内建对NHibernate的支持,有个NHibernateTemplate,对应配置文件如下。 里面会需要一个SessionFactory,这...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)