C#用NHibernate实现CRUD

2021-09-23 12:07:56 浏览数 (3)

hibernate.cfg.xml

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
 <session-factory>
  <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
  <property name="connection.connection_string">
   Data Source=zhou;Initial Catalog=AspNetStudy;User ID=sa;Password=jerry;
  </property>
  <property name="adonet.batch_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
  <property name="use_outer_join">true</property>
  <property name="command_timeout">10</property>
  <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
  <property name="proxyfactory.factory_class">
   NHibernate.ByteCode.Castle.ProxyFactoryFactory,
   NHibernate.ByteCode.Castle
  </property>
  <mapping assembly="NHibernateDemo"/>
 </session-factory>
</hibernate-configuration>

UserInfo.hbm.xml

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
 assembly="NHibernateDemo" namespace="NHibernateDemo">
 <class name="UserInfo">
  <id name="UserId" column="UserId">
   <generator class="native"/>
  </id>
  <property name="UserName"/>
  <property name="RealName"/>
  <property name="Age"/>
  <property name="Sex"/>
  <property name="Mobile"/>
  <property name="Phone"/>
  <property name="Email"/>
 </class>
</hibernate-mapping>

UserInfo.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Text;

namespace NHibernateDemo
{
    /// <summary>
    /// 数据库中UserInfo表的持久化类
    /// 作者:周公
    /// 博客地址:http://blog.csdn.net/zhoufoxcn
    /// 日期:2010-03-19
    /// </summary>
    public class UserInfo
    {
        public virtual int UserId { get; set; }
        public virtual string UserName { get; set; }
        public virtual string RealName { get; set; }
        public virtual int Age { get; set; }
        public virtual bool Sex { get; set; }
        public virtual string Mobile { get; set; }
        public virtual string Phone { get; set; }
        public virtual string Email { get; set; }
    }
}

NHibernateCRUD.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Text;
using Iesi.Collections;
using NHibernate;
using NHibernate.Cfg;

namespace NHibernateDemo
{
    /// <summary>
    /// 说明:这个类是为了演示NHibernate中的CRUD的用法
    /// 作者:周公(周金桥)
    /// 日期:2010-03-07
    /// </summary>
    public class NHibernateCRUD
    {
        private ISessionFactory sessionFactory;
        public NHibernateCRUD()
        {
            sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }

        public ISession GetSession()
        {
            return sessionFactory.OpenSession();
        }
        /// <summary>
        /// 统计用户总数
        /// </summary>
        /// <returns></returns>
        public int Count()
        {
            #region 方法一
            //ISession session = GetSession();
            //ISQLQuery query = session.CreateSQLQuery("select count(1) from UserInfo");
            //int count = query.List<int>()[0];
            //session.Close();
            //return count;
            #endregion

            #region 方法二
            ISession session = GetSession();
            IQuery query = session.CreateQuery("select count(c.UserId) from UserInfo c");
            //注意:不能对于count函数不能使用query.List<int>(),因为默认返回的数值类型是long
            //否则会抛出GenericADOException,异常描述是:Could not execute query[SQL: SQL not available]
            //InnerException: System.ArgumentException,InnerException描述是:"值“*”不是“System.Int32”类型,不能在此泛型集合中使用。rn参数名: value
            int count =(int)(query.List<long>()[0]);
            session.Close();
            return count;
            #endregion
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="info">用户实体</param>
        /// <returns></returns>
        public int Create(UserInfo info)
        {
            ISession session = GetSession();
            int newId=(int)(session.Save(info));
            session.Flush();
            session.Close();
            return newId;
        }
        /// <summary>
        /// 读取用户信息
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns></returns>
        public UserInfo Read(int userId)
        {
            ISession session = GetSession();
            UserInfo info=session.Get<UserInfo>(userId);
            session.Close();
            return info;
        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="info">用户实体</param>
        /// <returns></returns>
        public void Update(UserInfo info)
        {
            ISession session = GetSession();
            session.Update(info);
            session.Flush();
            session.Close();
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns></returns>
        public void Delete(int userId)
        {
            ISession session = GetSession();
            //在NHibernate中支持直接使用参数值、":" 参数名、?(类似于在Access中使用参数化SQL语句的方式,给参数赋值要按照参数出现的顺序来)等几种方式
            IQuery query = session.CreateQuery("delete from UserInfo where UserId=:UserId");
            //如果采用":" 参数名方式使用参数,那么给参数赋值时不需要在参数名前加":"号,如query.SetInt32(":UserId", userId);就会报错
            query.SetInt32("UserId", userId);
            int affectedRows = query.ExecuteUpdate();
            session.Close();
            //return affectedRows;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户实体</param>
        /// <returns></returns>
        public void Delete(UserInfo info)
        {
            ISession session = GetSession();
            session.Delete(info);
            session.Flush();
            session.Close();
        }

        /// <summary>
        /// 获取用户表中编号最大的用户
        /// </summary>
        /// <returns></returns>
        public int GetMaxUserId()
        {
            ISession session = GetSession();
            IQuery query=session.CreateQuery("select max(UserId) from UserInfo");
            int userId=query.List<int>()[0];
            session.Close();
            return userId;
        }
    }
}

单元测试 NHibernateTest.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NHibernateDemo;

namespace NUnitTest
{
    [TestFixture]
    public class NHibernateTest
    {
        private NHibernateCRUD instance = null;
        [SetUp]
        public void Initialize()
        {
            instance = new NHibernateCRUD();
        }
        [Test]
        /// <summary>
        /// 统计用户总数
        /// </summary>
        /// <returns></returns>
        public void Count()
        {
            Assert.Greater(instance.Count(), 0);
        }
        [Test]
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="info">用户实体</param>
        /// <returns></returns>
        public void Create()
        {
            UserInfo info = new UserInfo()
            {
                Age = 12,
                Email = "zzz@ccav.com",
                Mobile = "13812345678",
                Phone = "01012345678",
                RealName = "测试"   DateTime.Now.Millisecond.ToString(),
                Sex = true,
                UserName = "zhoufoxcn"   DateTime.Now.Millisecond.ToString()
            };
            instance.Create(info);
        }
        [Test]
        /// <summary>
        /// 读取用户信息
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns></returns>
        public void Read()
        {
            UserInfo info = instance.Read(1);
            Assert.NotNull(info);
        }
        [Test]
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="info">用户实体</param>
        /// <returns></returns>
        public void Update()
        {
            UserInfo info = instance.Read(1);
            info.RealName = "测试"   DateTime.Now.Millisecond.ToString();
            instance.Update(info);
        }
        [Test]
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns></returns>
        public void DeleteByID()
        {
            int userId = instance.GetMaxUserId();
            instance.Delete(userId);
        }

        [Test]
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户实体</param>
        /// <returns></returns>
        public void Delete()
        {
            int userId = instance.GetMaxUserId();
            UserInfo info = instance.Read(userId);
            Console.WriteLine("MaxUserId="   userId);
            instance.Delete(info);
        }
    }
}

0 人点赞