NHibernate实现CRUD

hibernate.cfg.xml

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

UserInfo.hbm.xml

<?xml version="1.0" encoding="utf-8"?><hibernate-mappingxmlns="urn:nhibernate-mapping-2.2"assembly="NHibernateDemo"namespace="NHibernateDemo"><classname="UserInfo"><idname="UserId"column="UserId"><generatorclass="native"/></id><propertyname="UserName"/><propertyname="RealName"/><propertyname="Age"/><propertyname="Sex"/><propertyname="Mobile"/><propertyname="Phone"/><propertyname="Email"/></class></hibernate-mapping>

UserInfo.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceNHibernateDemo{/// <summary>/// 数据库中UserInfo表的持久化类/// 作者:周公/// 博客地址:http://blog.csdn.net/zhoufoxcn/// 日期:2010-03-19/// </summary>publicclassUserInfo{publicvirtualintUserId{get;set;}publicvirtualstringUserName{get;set;}publicvirtualstringRealName{get;set;}publicvirtualintAge{get;set;}publicvirtualboolSex{get;set;}publicvirtualstringMobile{get;set;}publicvirtualstringPhone{get;set;}publicvirtualstringEmail{get;set;}}}

NHibernateCRUD.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingIesi.Collections;usingNHibernate;usingNHibernate.Cfg;namespaceNHibernateDemo{/// <summary>/// 说明:这个类是为了演示NHibernate中的CRUD的用法/// 作者:周公(周金桥)/// 日期:2010-03-07/// </summary>publicclassNHibernateCRUD{privateISessionFactory sessionFactory;publicNHibernateCRUD(){
            sessionFactory =newConfiguration().Configure().BuildSessionFactory();}publicISessionGetSession(){return sessionFactory.OpenSession();}/// <summary>/// 统计用户总数/// </summary>/// <returns></returns>publicintCount(){#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”类型,不能在此泛型集合中使用。\r\n参数名: valueint count =(int)(query.List<long>()[0]);
            session.Close();return count;#endregion}/// <summary>/// 创建用户/// </summary>/// <param name="info">用户实体</param>/// <returns></returns>publicintCreate(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>publicUserInfoRead(int userId){ISession session =GetSession();UserInfo info=session.Get<UserInfo>(userId);
            session.Close();return info;}/// <summary>/// 更新用户信息/// </summary>/// <param name="info">用户实体</param>/// <returns></returns>publicvoidUpdate(UserInfo info){ISession session =GetSession();
            session.Update(info);
            session.Flush();
            session.Close();}/// <summary>/// 删除用户/// </summary>/// <param name="userId">用户编号</param>/// <returns></returns>publicvoidDelete(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>publicvoidDelete(UserInfo info){ISession session =GetSession();
            session.Delete(info);
            session.Flush();
            session.Close();}/// <summary>/// 获取用户表中编号最大的用户/// </summary>/// <returns></returns>publicintGetMaxUserId(){ISession session =GetSession();IQuery query=session.CreateQuery("select max(UserId) from UserInfo");int userId=query.List<int>()[0];
            session.Close();return userId;}}}

单元测试 NHibernateTest.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingNUnit.Framework;usingNHibernateDemo;namespaceNUnitTest{[TestFixture]publicclassNHibernateTest{privateNHibernateCRUD instance =null;[SetUp]publicvoidInitialize(){
            instance =newNHibernateCRUD();}[Test]/// <summary>/// 统计用户总数/// </summary>/// <returns></returns>publicvoidCount(){Assert.Greater(instance.Count(),0);}[Test]/// <summary>/// 创建用户/// </summary>/// <param name="info">用户实体</param>/// <returns></returns>publicvoidCreate(){UserInfo info =newUserInfo(){Age=12,Email="[email protected]",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>publicvoidRead(){UserInfo info = instance.Read(1);Assert.NotNull(info);}[Test]/// <summary>/// 更新用户信息/// </summary>/// <param name="info">用户实体</param>/// <returns></returns>publicvoidUpdate(){UserInfo info = instance.Read(1);
            info.RealName="测试"+DateTime.Now.Millisecond.ToString();
            instance.Update(info);}[Test]/// <summary>/// 删除用户/// </summary>/// <param name="userId">用户编号</param>/// <returns></returns>publicvoidDeleteByID(){int userId = instance.GetMaxUserId();
            instance.Delete(userId);}[Test]/// <summary>/// 删除用户/// </summary>/// <param name="userId">用户实体</param>/// <returns></returns>publicvoidDelete(){int userId = instance.GetMaxUserId();UserInfo info = instance.Read(userId);Console.WriteLine("MaxUserId="+ userId);
            instance.Delete(info);}}}

你可能感兴趣的:(Hibernate)