zoukankan      html  css  js  c++  java
  • NHibernate开发入门

    首先,我们了解一下ORM是什么?
    ORM指对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。

    其次,我们需要了解.NET领域ORM框架有哪些?
    在.NET平台下,关于数据持久层框架非常多,以下是主要的5种:
    1.NHibernate
    2.NBear
    3.Castle ActiveRecord
    4.iBATIS.NET
    5.DAAB 微软

    使用过Java的朋友都不会对Hibernate陌生。由于之前的Java经历,所以我直接选择NHibernate作为ORM框架首选。那么NHibernate是什么?

    NHibernate是一个面向.NET环境的对象/关系数据库映射工具。对象/关系数据库映射(object/relational mapping,ORM)这个术语表示一种技术,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去。

    下面,我们做一个简单的NHibernate Demo。创建项目WinForm窗体项目,命名为CRMdemo,以下是解决方案截图:

    解决方案项目截图

    获取NHibernate

    NHibernate下载地址

    https://sourceforge.net/projects/nhibernate/files/NHibernate/4.0.3.GA/NHibernate-4.0.3.GA-bin.zip/download

    NHibernate项目地址

    https://sourceforge.net/projects/nhibernate/

    为了方便,下载后将NHibernate-4.0.3.GA-bin.zip解压缩至解决方案根目录下

    添加NHibernate Dll引用

    添加引用

    NHibernate-4.0.3.GA-binRequired_BinsNHibernate.dll

    NHibernate-4.0.3.GA-binRequired_BinsIesi.Collections.dll

    NHibernate-4.0.3.GA-binTestslog4net.dll

    NHibernate-4.0.3.GA-binTestsNHibernate.DomainModel.dll

    NHibernate-4.0.3.GA-binTests unit.framework.dll

    配置hibernate.cfg.xml

    复制NHibernate-4.0.3.GA-binConfiguration_TemplatesMSSQL.cfg.xml至binDebug下,重命名为hibernate.cfg.xml,并做如下配置

    <!-- This is the System.Data.dll provider for SQL Server -->
        <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
        <session-factory name="CRMDemo.Hibernate">
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.connection_string">
        Server=Your-PCSQLEXPRESS;initial catalog=crm;Integrated Security=SSPI
        </property>
        <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
            <mapping assembly="CRMDemo"/>
        </session-factory>
        </hibernate-configuration>

    在MSSQL中创建一张演示表employee

    创建员工表employee

    CREATE TABLE [dbo].[employee](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [name] [nvarchar](50) NULL,
        [age] [nchar](10) NULL,
        [gender] [nchar](10) NULL,
        [email] [nvarchar](100) NULL,
        [phonenum] [nvarchar](50) NULL,
         CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED 
        (
        [id] ASC
        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)  ON [PRIMARY]
        ) ON [PRIMARY]

    创建Employee.cs类

        public class Employee
        {
            public virtual int id { get; set; }
            public virtual string name { get; set; }
            public virtual int age { get; set; }
            public virtual string gender { get; set; }
            public virtual string email { get; set; }
            public virtual string phonenum { get; set; }
        }

    创建映射文件Employee.hbm.xml,其中字段名称必须和类属性名称一致,区分大小写。

    <?xml version="1.0" ?>
        <!--
        * By huiyaosoft.com
        * build date 2015-4-12 10:10
        -->
        <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
        <class 
        name="CRMDemo.Employee, CRMDemo" 
        discriminator-value="0" table="employee" >
        <id 
        name="id" type="int"
        unsaved-value="null">
              <column name="id" length="4" sql-type="4" not-null="true" unique="true"
                      index="PK_employee"/>
              <generator class="native" />
        <!-- unsaved-value used to be null and generator was increment in h2.0.3 -->
        </id>
        <property name="name" type="String">
        <column name="name" length="50" sql-type="nvarchar" not-null="false"/>
        </property>
            <property name="email" type="String">
              <column name="email" length="50" sql-type="nvarchar" not-null="false"/>
            </property>
            <property name="gender" type="String">
              <column name="gender" length="10" sql-type="nchar" not-null="false"/>
            </property>
            <property name="phonenum" type="String">
              <column name="phonenum" length="50" sql-type="nvarchar" not-null="false"/>
            </property>
            <property name="age" type="int">
              <column name="age" length="4" sql-type="int" not-null="false"/>
            </property>
        </class>
     </hibernate-mapping>

    设置Employee.hbm.xml为嵌入的资源

    增删改查代码

    添加命名空间

    using NHibernate;
    using NHibernate.Cfg;

    查询操作,CreateQuery或CreateSqlQuery

    Configuration cfg = new Configuration();
        cfg.Configure();
        ISessionFactory factory = cfg.BuildSessionFactory();
        ISession session = factory.OpenSession();
        IQuery query = session.CreateQuery("from Employee");
        IList<Employee> eList = query.List<Employee>();
        foreach (Employee item in eList)
        {
            this.textBox1.AppendText(string.Format("id:{0},name:{1},email:{2}
    ", item.id, item.name, item.email));
        }
        //ISQLQuery query = session.CreateSQLQuery("select * from employee").AddEntity(typeof(Employee)); 
        //IList<Employee> eList = query.List<Employee>();
        //foreach (Employee item in eList)
        //{
        //    Console.WriteLine("id:{0},name:{1},email:{2}
    ", item.id, item.name, item.email);
        //}
        session.Close();
        factory.Close();

    增加操作session.Save(Entity)

    Configuration cfg = new Configuration();
        cfg.Configure();
        ISessionFactory factory = cfg.BuildSessionFactory();
        ISession session = factory.OpenSession();
        ITransaction trans = session.BeginTransaction();
        Employee ee = new Employee();
        ee.age = 31;
        ee.name = "李四";
        ee.email = "zhang@163.com";
        ee.phonenum = "1358111111";
        ee.gender = "";
        session.Save(ee);
        trans.Commit();
        session.Close();
        factory.Close();
        this.textBox1.AppendText("已增加一条记录
    ");

    修改操作session.Save(Entity)

    Configuration cfg = new Configuration();
        cfg.Configure();
        ISessionFactory factory = cfg.BuildSessionFactory();
        ISession session = factory.OpenSession();
        ITransaction trans = session.BeginTransaction();
        IQuery query = session.CreateQuery("from Employee where id = :id").SetString("id","1");
        IList<Employee> eList = query.List<Employee>();
        foreach (Employee item in eList)
        {
            this.textBox1.AppendText("查询到一条记录
    ");
            this.textBox1.AppendText(string.Format("id:{0},name:{1},email:{2}
    ", item.id, item.name, item.email));
            item.email = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
           session.Save(item);
        }
        trans.Commit();
        query = session.CreateQuery("from Employee where id = :id").SetString("id", "1");
        eList = query.List<Employee>();
        foreach (Employee item in eList)
        {
            this.textBox1.AppendText("修改后记录
    ");
            this.textBox1.AppendText(string.Format("id:{0},name:{1},email:{2}
    ", item.id, item.name, item.email));
        }
       session.Close();
        factory.Close();

    删除操作session.Delete(Entity)

    Configuration cfg = new Configuration();
        cfg.Configure();
        ISessionFactory factory = cfg.BuildSessionFactory();
        ISession session = factory.OpenSession();
        ITransaction trans = session.BeginTransaction();
        IQuery query = session.CreateQuery("from Employee where name = :name").SetString("name", "李四");
        IList<Employee> eList = query.List<Employee>();
        foreach (Employee item in eList)
        {
            this.textBox1.AppendText("查询记录
    ");
            this.textBox1.AppendText(string.Format("id:{0},name:{1},email:{2}
    ", item.id, item.name, item.email));
            session.Delete(item);
        }
        trans.Commit();
        query = session.CreateQuery("from Employee where name = :name").SetString("name", "李四");
        eList = query.List<Employee>();
        foreach (Employee item in eList)
        {
            this.textBox1.AppendText("删除后记录
    ");
        }
        session.Close();
        factory.Close();

    来源:http://www.huiyaosoft.com/html/nhibernate.htm

    本项目演示例子点击下载

  • 相关阅读:
    LinkedList -链表集合
    java包装类,自动装箱,拆箱,以及基本数据类型与字符串的转换
    StringBuilder -字符串缓冲区,节约内层空间变长数组
    System的两常用个静态方法
    StringBuilder
    mysql
    空房间
    数据结构占坑
    sql语句优化
    editPlus快捷键
  • 原文地址:https://www.cnblogs.com/youmingkuang/p/5578370.html
Copyright © 2011-2022 走看看