关闭

Spring.Net&NHibernate 学习 5

1278人阅读 评论(4) 收藏 举报
创建数据库: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!
换行:数据插入数据库
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:436588次
    • 积分:4381
    • 等级:
    • 排名:第6829名
    • 原创:71篇
    • 转载:96篇
    • 译文:0篇
    • 评论:49条
    最新评论