zoukankan      html  css  js  c++  java
  • Nhibernate系列学习之(二) 简单增删改查

    实例中解决方案简单的创建三层架构,符合开发过程中最简单的运用;

    1:首先在数据库中创建一个表T_School,脚本如下:

    复制代码
    复制代码
    USE [TestDb]
    GO
    /****** 对象:  Table [dbo].[T_School]    脚本日期: 03/01/2014 19:45:45 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[T_School](
        [ID] [uniqueidentifier] NOT NULL,
        [SchoolName] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NULL,
        [BuildDate] [datetime] NULL,
        [Address] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
        [IsSenior] [bit] NULL,
        [StudentNum] [int] NULL
    ) ON [PRIMARY]
    复制代码
    复制代码

    2:创建实体层Model,实体中的字段还以virtual进行修饰

    复制代码
    复制代码
    namespace Wujy.ModelLibrary.Entity
    {
        public class SchoolModel
        {
            /// <summary>
            /// ID
            /// </summary>
            public virtual Guid ID
            {
                get;
                set;
            }
            /// <summary>
            /// SchoolName
            /// </summary>
            public virtual string SchoolName
            {
                get;
                set;
            }
            /// <summary>
            /// BuildDate
            /// </summary>
            public virtual DateTime? BuildDate
            {
                get;
                set;
            }
            /// <summary>
            /// Address
            /// </summary>
            public virtual string Address
            {
                get;
                set;
            }
            /// <summary>
            /// 高级
            /// </summary>
            public virtual bool IsSenior
            {
                get;
                set;
            }
            /// <summary>
            /// 人数
            /// </summary>
            public virtual int? StudentNum
            {
                get;
                set;
            }        
        }
    }
    复制代码
    复制代码

    2.1 此处还增加NHibernate需要的XML映射文件,以实体名+hbm.xml结尾并且还要设置其生成操作为"嵌入的资源";其中Class中的name是指实体类的完整名及类库名称,代码如下

    复制代码
    复制代码
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Maticsoft" namespace="Maticsoft">
      <class name="Wujy.ModelLibrary.Entity.SchoolModel, Wujy.ModelLibrary" table="T_School">
        <id name="ID" column="ID" type="Guid"></id>
        <property name="SchoolName" column="SchoolName" type="string"  />
        <property name="BuildDate" column="BuildDate" type="DateTime"  />
        <property name="Address" column="Address" type="string"  />
        <property name="IsSenior" column="IsSenior" type="bool"  />
        <property name="StudentNum" column="StudentNum" type="int"  />
      </class>
    </hibernate-mapping>
    复制代码
    复制代码

    3:创建一个类库作为DAL层,此处我们引用NHibernate两个DLL,分别为NHibernate.dll及Iesi.Collection.dll;此处创建一个帮助类NHibernateHelper用于ISessionFactory;

    复制代码
    复制代码
    using NHibernate;
    using NHibernate.Cfg;
    
    namespace Wujy.DalLibrary.DalHelp
    {
        public class NHibernateHelper
        {
            private ISessionFactory _sessionFactory;
            public NHibernateHelper()
            {
                _sessionFactory = GetSessionFactory();
            }
            private ISessionFactory GetSessionFactory()
            {
                return (new Configuration()).Configure().BuildSessionFactory();
            }
            public ISession GetSession()
            {
                return _sessionFactory.OpenSession();
            }
        }
    }
    复制代码
    复制代码

    3.1:创建类SchoolDal并把一些操作的代码写入,如查不用transaction.Commit()则要运和isession.Flush()否则无法执行SQL就没有效果:

    复制代码
    复制代码
    using Wujy.ModelLibrary.Entity;
    using NHibernate;
    using Wujy.DalLibrary.DalHelp;
    
    namespace Wujy.DalLibrary
    {
        public class SchoolDal
        {
            private ISession isession;
    
            public SchoolDal()
            {
                isession = new NHibernateHelper().GetSession();
            }
    
            public void Add(SchoolModel model)
            {
                //如查不用transaction.Commit()则要运和isession.Flush()否则无法执行SQL就没有效果
                //ITransaction transaction = isession.BeginTransaction();
                //isession.Save(model);
                //transaction.Commit();
                isession.Save(model);
                isession.Flush();
            }
    
            public bool Update(SchoolModel model)
            {
                try
                {
                    isession.Update(model);
                    isession.Flush();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    isession.Close();
                }
            }
    
            public bool Delete(SchoolModel model)
            {
                try
                {
                    isession.Delete(model);
                    isession.Flush();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    isession.Close();
                }
            }
    
            public SchoolModel GetSchoolById(Guid ID)
            {
                return isession.Get<SchoolModel>(ID);
            }
    
            public IList<SchoolModel> GetSchoolList()
            {
                IList<SchoolModel> list = null;
                list = isession.QueryOver<SchoolModel>().List();
                return list;
            }
        }
    }
    复制代码
    复制代码

    4:因为本实例重点是对NHibernate运用,对于逻辑层就简单的引用;代码也很简单:

    复制代码
    复制代码
    using Wujy.ModelLibrary.Entity;
    using Wujy.DalLibrary;
    
    namespace Wujy.BllLibrary
    {
        public class SchoolBll
        {
            public static void Add(SchoolModel model) 
            {
                new SchoolDal().Add(model);
            }
    
            public static bool Update(SchoolModel model)
            {
                return new SchoolDal().Update(model);
            }
    
            public static bool Delete(SchoolModel model)
            {
                return new SchoolDal().Delete(model);
            }
    
            public static SchoolModel GetSchoolById(Guid ID)
            {
                return new SchoolDal().GetSchoolById(ID);
            }
    
            public static IList<SchoolModel> GetSchoolList()
            {
                return new SchoolDal().GetSchoolList();
            }
        }
    }
    复制代码
    复制代码

    5:WebUI除简单调用BLL层外,另一个比较重要是NHibernate连接数据库的配置文件,其中其属性复制到输出目录改为"始终复制";Hibernate.cfg.xml内容:

    复制代码
    复制代码
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <session-factory name="NHibernateConfig">
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.connection_string">Server=localhost;uid=sa;password=admin;database=TestDb</property>
        <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
        <property name="command_timeout">10</property>
        <mapping assembly="Wujy.ModelLibrary"/><!--表示映射Wujy.ModelLibrary实体程序集下的所有类,就不用一个个去映射-->
      </session-factory>
    </hibernate-configuration>
    复制代码
    复制代码
  • 相关阅读:
    Git修改注释
    数组和切片的区别
    SpringBoot启动报:Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    eclipse中web.xml报:The content of element type "web-app" must match "(icon?,display- name?,
    eclipse错误: 在类xxx中找不到 main 方法, 请将 main 方法定义为: public static void main(String[] args) 否则 JavaFX 应用程序类必须扩展javafx.application.Application
    idea Cannot resolve method ‘setAttribute(java.lang.String, java.lang.String)/不能使用pageContext.setAttribute()
    解决Nginx启动报nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
    数据仓库开发规范
    详解会话技术cookie、session和token
    Requests爬虫包及解析工具 xpath、正则、Beautiful Soup
  • 原文地址:https://www.cnblogs.com/jiangshuai52511/p/7229995.html
Copyright © 2011-2022 走看看