NHibernate增删改查

我们采用Model→DAL→BLL→UI的模式利用NHibernate写一个增删改查

先创建一个类库Model,然后创建一个类Product.cs

技术分享
namespace Model
{
    public class Product
    {
        /// <summary>
        /// ID
        /// </summary>
        public virtual Guid ID { get; set; }

        /// <summary>
        /// 编号
        /// </summary>
        public virtual string Code { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// 规格
        /// </summary>
        public virtual string QuantityPerUnit { get; set; }

        /// <summary>
        /// 单位
        /// </summary>
        public virtual string Unit { get; set; }

        /// <summary>
        /// 售价
        /// </summary>
        public virtual decimal SellPrice { get; set; }

        /// <summary>
        /// 进价
        /// </summary>
        public virtual decimal BuyPrice { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public virtual string Remark { get; set; }
    }
}
Product.cs

紧接着在类库下面在创建Product.hbm.xml文件,注意:要修改属性“生成操作”改成“嵌入的资源”

技术分享
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Model" namespace="Model">
  <class name="Product" table="T_Product" lazy="true" >
    <id name="ID" column="ID" type="Guid" >
      <generator class="assigned" />
    </id>

    <property name="Code" type="string">
      <column name="Code" length="50"/>
    </property>

    <property name="Name" type="string">
      <column name="Name" length="50"/>
    </property>

    <property name="QuantityPerUnit" type="string">
      <column name="QuantityPerUnit" length="50"/>
    </property>

    <property name="Unit" type="string">
      <column name="Unit" length="50"/>
    </property>


    <property name="SellPrice" type="decimal">
      <column name="SellPrice" precision="14" scale="2"/>
    </property>

    <property name="BuyPrice" type="decimal">
      <column name="BuyPrice" precision="14" scale="2"/>
    </property>

    <property name="Remark" type="string">
      <column name="Remark" length="200"/>
    </property>

  </class>
</hibernate-mapping>
Product.hbm.xml

注意:1.根节点下的程序集assembly和命名空间namespace,一般跟类库的名字一样

   2.class节点有一个name属性表示要映射哪个类,很显然是Product,还有一个table属性表示要映射哪个表

技术分享

好了Model层搞定了,接下来就是DAL层了

创建一个类库DAL,这个层干的事多一点,先添加引用吧,

NHibernate.dll这个是必须的

Iesi.Collections.dll就引用这个两个吧,以后用到了在引好吧!!!

接着在类库下面创建一个文件夹就叫DalHelp,然后在该文件夹下创建一个类叫NHibernateHelper,它主要是用来构建Session工厂,以及创建Session实例

技术分享
namespace DAL.DalHelp
{
    public class NHibernateHelper
    {
        #region 构建Session工厂
        private ISessionFactory _sessionFactory;
        public NHibernateHelper()
        {
            _sessionFactory = GetSessionFactory();
        }
        private ISessionFactory GetSessionFactory()
        {
            return (new Configuration()).Configure().BuildSessionFactory();
        }
        #endregion

        #region 创建Session实例
        public ISession GetSession()
        {
            return _sessionFactory.OpenSession();
        }
        #endregion
    }
}
NHibernateHelper

然后再在类库下面添加一个数据访问类ProductDAL,这个类主要是创建Session实例,写增删改查的方法

技术分享
namespace DAL
{
    public class ProductDAL
    {
        #region 创建Session实例
        private ISession session;
        public ProductDAL()
        {
            session = new NHibernateHelper().GetSession();
        }
        #endregion

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        public void Add(Product model)
        {
            session.Save(model);
            session.Flush();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(Product model)
        {
            try
            {
                session.Update(model);
                session.Flush();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                session.Close();
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Delete(Product model)
        {
            try
            {
                session.Delete(model);
                session.Flush();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                session.Close();
            }
        }
        /// <summary>
        /// 根据Id获取一个对象
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public Product GetProductById(Guid ID)
        {
            return session.Get<Product>(ID);
        }
        /// <summary>
        /// 加载列表信息
        /// </summary>
        /// <returns></returns>
        public IList<Product> GetProductList()
        {
            IList<Product> list = null;
            list = session.QueryOver<Product>().List();
            return list;
        }
    }
}
ProductDAL

技术分享

OK刀层写完了,也不多吧~~

该写BLL层了吧,里面就只有一个类ProductBLL,就是调用数据访问层的一坨方法,除了return就是return

技术分享
namespace BLL
{
    public class ProductBLL
    {
        public static void Add(Product model)
        {
            new ProductDAL().Add(model);
        }
        public static bool Update(Product model)
        {
            return new ProductDAL().Update(model);
        }
        public static bool Delete(Product model)
        {
            return new ProductDAL().Delete(model);
        }
        public static IList<Product> GetProductList()
        {
            return new ProductDAL().GetProductList();
        }
        public static Product GetProductById(Guid ID)
        {
            return new ProductDAL().GetProductById(ID);
        }
    }
}
ProductBLL

技术分享

OK,BLL层也写完了,接下来干嘛,该创建一个web程序了,用WebForm方式吧

技术分享

步骤1.创建一个XML文件hibernate.cfg.xml

技术分享
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory name="NHibernateTest">
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">
      server=.;database=NHibernateDemo;uid=sa;pwd=123;
    </property>
    <property name="adonet.batch_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="use_outer_join">true</property>
    <property name="command_timeout">60</property>
    <property name="hbm2ddl.auto">update</property>
    <property name="query.substitutions">true 1, false 0, yes Y, no N</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    <mapping assembly="Model"/>
  </session-factory>
</hibernate-configuration>
hibernate.cfg.xml

步骤2.复制两个东东到你的Web应用程序下面LinFu.DynamicProxy.dll和NHibernate.ByteCode.LinFu.dll,别忘了对这两个文件的属性进行修改,改成“始终复制”

步骤3.创建一个aspx页面,这里我们就简单一点拖五个服务端控件吧,分别代表增删改查和查一个

技术分享
/// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            Product product = new Product();
            product.ID = Guid.NewGuid();
            product.Code="9527";
            product.Name = ".NET之美";
            product.QuantityPerUnit = "20x1";
            product.Unit = "";
            product.SellPrice = 25M;
            product.BuyPrice = 10M;
            product.Remark = "好看";
            try
            {
                BLL.ProductBLL.Add(product);
                Response.Write("添加成功");
            }
            catch (Exception ex)
            {
                Response.Write("出现异常:" + ex.ToString());
            }
        }
添加的代码
技术分享
/// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Delete_Click(object sender, EventArgs e)
        {
            Product product = new Product();
            //条件
            product.ID = Guid.Parse("96BF4775-B0AE-4FEE-A36C-CDD67D84BFAC");
            if(ProductBLL.Delete(product))
            {
                Response.Write("删除成功");
            }
            else
            {
                Response.Write("删除失败");
            }
        }
删除的代码
技术分享
/// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Update_Click(object sender, EventArgs e)
        {
            Product product = new Product();
            product.ID = Guid.Parse("98D81CEA-36E9-45DF-A9BA-BC766576937A");
            product.Code = "9527";
            product.Name = "少妇白洁";
            product.QuantityPerUnit = "20x1";
            product.Unit = "";
            product.SellPrice = 25M;
            product.BuyPrice = 10M;
            product.Remark = "好看";
            if(ProductBLL.Update(product))
            {
                Response.Write("修改成功");
            }
            else
            {
                Response.Write("修改失败");
            }
        }
修改的代码
技术分享
/// <summary>
        /// 查询所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_List_Click(object sender, EventArgs e)
        {
            IList<Product> list= ProductBLL.GetProductList();
            foreach (var item in list)
            {
                Response.Write("ID:" + item.ID + "名字:" + item.Name + "</br>");
            }
        }
查询所有信息的代码
技术分享
/// <summary>
        /// 根据Id查询一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_OneModel_Click(object sender, EventArgs e)
        {
            Product product = new Product();
            product = ProductBLL.GetProductById(Guid.Parse("98D81CEA-36E9-45DF-A9BA-BC766576937A"));
            Response.Write(product.ID + "</br>" + product.Name);
        }
根据Id查询一条

好了,写完了,大家试试吧~~

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。