Nhibernate学习笔记

ORM

对象关系映射(Object Relational Mapping,简称ORM)是一种为了解决面向对象关系数据库存在的互不匹配的现象的技术。

ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。 本质上就是将数据从一种形式转换到另外一种形式

Nhibernate步骤:

1.在数据库中创建把.Net类持久化的对应表.(建数据库)

2.创建需要被持久化的.Net类.(建Model)

3.创建映射文件, 告诉NH怎样持久化这些类的属性.(建映射文件XML)

4. 创建NH的配置文件,以告诉NH怎样连接数据库.

5.使用NH提供的API.

 
常用接口:

ISession

ISession是面向用户的主要接口,主要用于对象持久化,数据加载等操作,支持数据库事务,它隐藏了NHB内部复杂的实现细节。

ISessionFatory(不要反复去创建它)

ISessionFactory是NHB内部的核心类,它维护到持久机制(数据库)的连接并对它们进行管理,同时还会保存所有持久对象的映射信息

ITransaction(事务)

ITransaction是NHB的事务处理接口,它只是简单的封装了底层的数据库事务。

IQuery

IQuery是HQL数据加载接口,HQL(Hibernate Query Language)是NHB专用的面向对象的数据查询语言,它与数据库的SQL有些类似,但功能更强大!

例:

1.创建数据库,建表t_Person(t_Id,t_Name)

2.创建项目,创建对象Person

3.映射文件*.hbm.xml文件

wps_clip_image-13770

4.创建对象与表之间的映射文件*.hbm.xml

*****将*.hbm.xml文件的属性-->生成操作-->嵌入的资源

wps_clip_image-13904

编译该项目----将对象以及对象的映射文件封装起来

5、创建C/S项目来实现我们的体验

    5.1引用文件NHibernate.dll 、Test.Entitydll

    5.2在App.config里面配置NHibernate

图片1

注意:<property name="connection.driver">NHibernate.Connection.ConnectionProvider,NHibernate</property>

wps_clip_image-14381

NhibernateDemo

Form1
  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows.Forms;
  9 using NHibernate;
 10 using NHibernate.Cfg;
 11 using NHibernate.Connection;
 12 using Test.Entity;
 13 using System.Collections;
 14 
 15 namespace NhiberNateDemo
 16 {
 17     public partial class Form1 : Form
 18     {
 19         ISession session = null;
 20         ISessionFactory factory = null;
 21         ITransaction trans = null;
 22         public Form1()
 23         {
 24             InitializeComponent();
 25         }
 26 
 27         private void Form1_Load(object sender, EventArgs e)
 28         {
 29             //读取配置文件
 30             //1.读取所有的映射文件--必须是嵌入资源
 31             Configuration config = new Configuration().AddAssembly("Test.Entity");
 32             //2.创建Session工厂,负责持久化连接以及OR映射,该对象开销比较大
 33             //一般我们建议用单例(静态)模式来处理
 34             factory = config.BuildSessionFactory();
 35             //3.创建一个可用于用户级别的操作对象
 36             session = factory.OpenSession();
 37             //4.开启事务
 38 
 39         }
 40 
 41         //新增
 42         private void btn_Add_Click(object sender, EventArgs e)
 43         {
 44             trans = session.BeginTransaction();
 45             //5.使用Nhibernate的现有API
 46             //体验过程。。。。
 47             try
 48             {
 49                 T_Person p = new T_Person();
 50                 p.t_Name = this.txt_Name.Text;
 51                 //将对象保存到数据库
 52                 //将对象p必须转化为数据库能识别的SQL语句
 53                 //由于IsessionFactory已经保存了所有OR映射
 54                 //ISession能根据相应的方言来实现SQL
 55                 session.Save(p);
 56                 trans.Commit();
 57             }
 58             catch (Exception)
 59             {
 60 
 61                 trans.Rollback();
 62             }
 63         }
 64 
 65         //搜索
 66         private void btn_search_Click(object sender, EventArgs e)
 67         {
 68             try
 69             {
 70                 this.txt_Name.Enabled = true;
 71                 trans = session.BeginTransaction();
 72                 //查找ID编号为2的人
 73                 //3--->ID属性---OR---->sql的where语句
 74                 T_Person p = (T_Person)session.Get(typeof(T_Person), int.Parse(this.txt_Id.Text));
 75                 //Console.WriteLine(p);
 76                 this.txt_Name.Text = p.t_Name;
 77             }
 78             catch (Exception)
 79             {
 80 
 81                 this.txt_Name.Text = "错误";
 82                 this.txt_Name.Enabled = false;
 83             }
 84         }
 85 
 86         //更新
 87         private void btn_update_Click(object sender, EventArgs e)
 88         {
 89             try
 90             {
 91                 trans = session.BeginTransaction();
 92                 //根据提供的ID找到对象
 93                 T_Person p = (T_Person)session.Get(typeof(T_Person), int.Parse(this.txt_Id.Text));
 94                 //修改对象的属性
 95                 p.t_Name = this.txt_Name.Text;
 96                 //将修改反映到数据库
 97                 session.Update(p);
 98                 trans.Commit();
 99             }
100             catch (Exception)
101             {
102 
103                 trans.Rollback();
104             }
105         }
106 
107         //删除
108         private void btn_delete_Click(object sender, EventArgs e)
109         {
110             try
111             {
112                 trans = session.BeginTransaction();
113                 T_Person p = (T_Person)session.Get(typeof(T_Person), int.Parse(this.txt_Id.Text));
114                 session.Delete(p);
115                 trans.Commit();
116             }
117             catch (Exception)
118             {
119                 trans.Rollback();
120             }
121 
122         }
123 
124 
125 
126         //HQL
127         private void btn_Hql_Click(object sender, EventArgs e)
128         {
129             //HQL体验----HQL是针对对象的查询语言
130             //1.查询所有人的信息
131             //IQuery Query = session.CreateQuery("from T_Person");
132             //IList<T_Person> person = Query.List<T_Person>();
133             //person.p1();
134 
135            //2.查询编号为9的的信息
136             //IQuery query2 = session.CreateQuery("from T_Person where t_Id=9");
137             //query2.List<T_Person>().p1();
138 
139             //3.查询名字中有a的人
140             //IQuery query3 = session.CreateQuery("from T_Person where T_Name like '%a%'");
141             //query3.List<T_Person>().p1();
142             
143             //4.查询编号大于5的人
144             //session.CreateQuery("from T_Person p where t_Id>5").List<T_Person>().p1();
145 
146             //5.聚合函数的使用----统计人数
147             //session.CreateQuery("select count(t_Id) from T_Person p").List().p2();
148 
149             //6.传参数1(?)
150             IQuery query6 = session.CreateQuery("from T_Person as p  where p.t_ID>?");
151             query6.SetParameter(0, 7);
152             query6.List<T_Person>().p1();
153 
154             ////7.传参数2(:)
155             //IQuery query6 = session.CreateQuery("from T_Person where t_Id>:id");
156             //query6.SetParameter("id", 12);
157             //query6.List<T_Person>().p1();
158 
159             ////8.查询指定范围数据:3-7条(一共5条)
160             //IQuery query8 = session.CreateQuery("from T_Person");
161             //query8.List<T_Person>().Skip<T_Person>(3).Take<T_Person>(5).ToList<T_Person>().p1();
162             //用ICriteria接口实现可能更加方便
163         }
164     }
165     
166     //对Ilist<Person>类型数据的输出建议用C#3.0的【扩展方法】
167     public static class ExtraClass
168     {
169         public static void p1(this IList<T_Person> p)
170         {
171             IEnumerator<T_Person> ie = p.GetEnumerator();
172             Console.WriteLine("\n--------------------\n");
173             while (ie.MoveNext())
174             {
175                 Console.WriteLine(ie.Current.ToString());
176             }
177             Console.WriteLine("\n--------------------\n");
178         }
179 
180         public static void p2(this IList p)
181         {
182             IEnumerator ie = p.GetEnumerator();
183             Console.WriteLine("\n--------------------\n");
184             while (ie.MoveNext())
185             {
186                 Console.WriteLine(ie.Current.ToString());
187             }
188             Console.WriteLine("\n--------------------\n");
189         }
190     }
191 }
App.config
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <configSections>
 4     <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" requirePermission="false"/>
 5     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
 6   </configSections>
 7 <!-- 
 8 This template was written to work with NHibernate.Test.                  这个模板是写入NHibernate.Test一起工作.
 9 Copy the template to your                                                NHibernate.复制模板来你的NHibernate.
10 Test project folder and rename it in hibernate.cfg.                      测试项目文件夹,然后在hibernate.cfg重命名它
11 xml and change it for your own use before compile tests in VisualStudio. xml和改变它对您的VisualStudio前使用编译测试。
12 -->
13 <!-- This is the System.Data.dll provider for SQL Server -->
14 <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
15     <session-factory>  
16     <!--<property name="connection.driver">NHibernate.Connection.ConnectionProvider,NHibernate</property>-->
17     <!--连接驱动类-->
18         <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>  
19         <property name="connection.connection_string">
20       Server=.\SQLEXPRESS;database=Nhibernate;uid=sa;pwd=sa;
21     </property>
22     <!--是否显示SQL语句-->
23         <property name="show_sql">true</property>
24     <!--方言:不同数据库有不同的方言-->
25         <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
26     <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
27     </session-factory>
28 </hibernate-configuration>
29   
30 </configuration>

Test

Person.cs
 1 using System;
 2 
 3 //Nhibernate Code Generation Template 1.0
 4 //author:MythXin
 5 //blog:www.cnblogs.com/MythXin
 6 //Entity Code Generation Template
 7 namespace Test.Entity
 8 {
 9     //T_Person
10     public class T_Person
11     {
12 
13         /// <summary>
14         /// t_ID
15         /// </summary>
16         public virtual int t_ID
17         {
18             get;
19             set;
20         }
21         /// <summary>
22         /// t_Name
23         /// </summary>
24         public virtual string t_Name
25         {
26             get;
27             set;
28         }
29 
30         public override string ToString()
31         {
32             return "编号:\t" + t_ID + "\t姓名:" + t_Name;
33         }
34     }
35 }
Person.hbm.xml
 1 <?xml version="1.0"  encoding="utf-8" ?>
 2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Test.Entity" namespace="Test.Entity">
 3   <class name="Test.Entity.T_Person, Test.Entity" table="T_Person">
 4     <id name="t_ID" column="t_ID" type="int" unsaved-value="0">
 5       <generator class="native" />
 6     </id>
 7     <property name="t_Name" column="t_Name" type="String"  />
 8 
 9   </class>
10 </hibernate-mapping>
原文地址:https://www.cnblogs.com/tangge/p/2555439.html