Nhibernate 4.0 教程

目录

1.      下载Nhibernate 4.04. 1

2.      入门教程... 2

3.      测试项目详解... 3

4.      总结... 7

附:关联知识点... 7

知识点1:C#静态构造函数... 7

知识点2:关于Visual Studio文件生成操作... 8

前言:

为什么会有这个框架?这就牵扯进了Java和C#的恩恩怨怨,Java是开源的面向对象语言的代表,围绕Java的有不计其数的开源框架,其中ORM框架(不要问我什么是ORM框架)中的最耀眼的代表就是Hibernate;C#也是Microsoft紧跟在Java后面推出的面向对象的语言,这两个相似度太大了(我读书自己学习的Java,后面C#就没特殊的学习过,直接就进行拿来用了),.NET开发者也参照Hibernate开发了一个针对.NET平台下的ORM 框架,也就是Nhibernate。

开发环境:

Windows 7

Visual Studio 2013

Nhibernate 4.04

Microsoft Sql Server 2012

  1. 下载Nhibernate 4.04

直接下载 官网地址http://nhibernate.info/(自己下载网速真的好慢)

NHibernate is a mature, open source object-relational mapper for the .NET framework. It's actively developed, fully featured and used in thousands of successful projects.

官网介绍了Nhibernate是针对.NET框架的成熟的、开源的面向关系型数据库映射(ORM).

或者使用VS2013附带的NuGet管理程序直接安装(NuGet,.NET下面一个开源的程序包管理工具):Install-Package Nhibernate(非常的快)

  1. 入门教程

新建一个项目NHOne和测试程序,并且添加对于该项目的测试项目,项目架构如下:

划重点:其中对于Nhibernate的配置文件(hibernate.cfg.xml与ClassMapping文件,对于生成的操作,必须选择始终复制和嵌入式资源。(不然编译调试的时候会出现bug,比如没有Model Class的Mapping等等)。

  1. 测试项目详解

3.1     初始化C#解决方案NHOne(控制台应用程序和对应的测试项目)

给每一个项目添加Nhibernate引用,测试项目也需要(直接NuGet命令安装即可)

3.2     编写NHibernate配置文件

在NHOne的根目录下添加hibernate.cfg.xml文件(生成操作嵌入式资源和始终复制),在文档属性中架构选择hibernate-configuration-2.2 & hibernate-mapping-2.2两个文件,这样编写hibernate.cfg.xml就会有自动提示的功能(这两个文件在我们解决方案NHOne的packages/Nhibernate目录中)

hibernate.cfg.xml 具体内容如下:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

<session-factory>

<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>

<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

<property name="connection.connection_string">Data Source=localhost;user=sa;password=12345;Initial Catalog=test</property>

<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>

<property name="show_sql">true</property>

<property name="hbm2ddl.auto">update</property>

<!--Mapping files 嵌入式资源 表格table 名字不可以是user-->

<mapping  assembly="NHOne"/>

</session-factory>

</hibernate-configuration>

<mapping assembly=”NHOne”/> 这里写的是项目的名字,然后就会搜寻项目下面所有的后缀是.hbm.xml的文件,也可以手动自己添加,比较麻烦,有机会再详细讲解。

3.3     编写Model Class “User”

所有的属性都是使用virtual来修饰(延迟加载有用),添加对应的get set方法

在MSServer 中,user 是关键字,因此不能够有user的表格,可以使用其他来代替

在实际应用中,每一个model类,很可能需要提供Equals() HashCode() ToString()方法的重写

namespace NHOne.Model

{

public class User

{

private string id;

private string username;

private string password;

private char gender; //"F" & "M"

private int age;

private string phone;

public User()

{

}

public User(string username, string password, char gender, int age, string phone)

{

this.username = username;

this.password = password;

this.gender = gender;

this.age = age;

this.phone = phone;

}

public User(string id, string username, string password, char gender, int age, string phone)

{

this.id = id;

this.username = username;

this.password = password;

this.gender = gender;

this.age = age;

this.phone = phone;

}

public virtual string Id { get; set; }

public virtual string Username { get; set; }

public virtual string Password { get; set; }

public virtual char Gender { get; set; }

public virtual int Age { get; set; }

public virtual string Phone { get; set; }

public override bool Equals(object obj)

{

if (this == obj)

{

return true;

}

User user = obj as User;

if (user == null)

{

return false;

}

else

{

return this.Username.Equals(user.Username);

}

}

public override int GetHashCode()

{

return Username.GetHashCode();

}

public override string ToString()

{

return "id:" + Id + ";  Username:" + Username + ";  Password:" + Password + ";  Gender:" + Gender + ";  Age:" + Age + ";    Phone:" + Phone;

}

}

}

3.4  编写Model的Mapping文件

位于Mapping目录下面新建文件User.hbm.xml文件(嵌入式资源,添加文件的架构为hibernate-mapping-2.2.xml),红色部分 assembly是项目的名称,namespace是在项目中Model类的命名空间,如果省略的话,需要在后面的class name属性中填写完整的名字空间和类名。

注意table的名字不能写成user,否则报错,因为user是数据库的关键字

内容如下:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHOne" namespace="NHOne.Model" default-lazy="true">

<class name="User" table="client">

<id name="Id">

<column name="user_id" sql-type="char(32)" not-null="true"/>

<generator class="uuid.hex"/>

</id>

<property name="Username" column="username"  not-null="true"/>

<property name="Password" column="password" not-null="true" />

<property name="Gender"   column="gender"   />

<property name="Age"      column="age"      />

<property name="Phone"    column="phone"    />

</class>

</hibernate-mapping>

3.5    编写NHibernate的帮助类,初始化NHibernate的环境,获取Session

在Util命名空间下,添加YangNHibernate的类,具体内容如下:

namespace NHOne.Util

{

public class YangNHibernate

{

private static readonly  ISessionFactory sessionFactory;

private static string HibernateHbmXmlFileName = "hibernate.cfg.xml";

//private static ISession session

static YangNHibernate()

{

sessionFactory = new Configuration().Configure().BuildSessionFactory();

}

public static ISessionFactory getSessionFactory()

{

return sessionFactory;

}

public static ISession getSession()

{

return sessionFactory.OpenSession();

}

public static void closeSessionFactory()

{

}

}

}

3.6    编写测试代码

在测试类中测试保存User到数据库,使用事务的机制

[TestMethod]

public void TestSaveUser()

{

User user = createUser();

ISession session  = YangNHibernate.getSession();

ITransaction tx = session.BeginTransaction();

session.Save(user);

tx.Commit();

session.Close();

}

调试程序:

  1. 总结

NHibernate是C#程序员,参照Java的ORM框架Hibernate实现的一个开源项目,在C#中项目开发中非常的便捷高效,让程序猿从复杂的SQL语句中解放出来,对于项目的模块化非常好用。

测试项目的源代码地址:

https://github.com/hbhzsysutengfei/NHibernateOne.git

参考文档:

  1. NHibernate官方网站 http://nhibernate.info/
  2. MSDN for C#:https://msdn.microsoft.com/zh-cn/library/k9x6w0hc(v=vs.120).aspx

附:关联知识点

知识点1:C#静态构造函数

C#关于静态构造函数的知识,自动调用初始化静态的成员属性,尤其是readonly修饰的静态属性,与Java中的静态代码块类似。

参考MSDN给出的解释:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

https://msdn.microsoft.com/zh-cn/library/k9x6w0hc(v=vs.120).aspx

因为静态构造函数是.NET自动调用的,因此改代码块就无需使用修饰符修饰。

关于C#静态构造函数的特征,具体如下:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

知识点2:关于Visual Studio文件生成操作

Visual Studio生成操作有以下几个选项:

Non(无):也就是在项目生成的时候不进行任何的操作,在生成的目录中没有此文件,一般用于项目描述文件.

Content(内容):也就是将文件直接复制到输出目录中,一般用于html等静态文件.

Compile(编译):编译代码文件,通常的代码文件需要编译

Embedded Resource(嵌入式资源):将该文件作为DLL或可执行文件嵌入到主目录中,通常用于资源文件,比如Nhibernate的配置文件等等。

Nhibernate 4.0 教程入门的更多相关文章

  1. Asp.Net MVC4.0 官方教程 入门指南之五--控制器访问模型数据

    Asp.Net MVC4.0 官方教程 入门指南之五--控制器访问模型数据 在这一节中,你将新创建一个新的 MoviesController类,并编写代码,实现获取影片数据和使用视图模板在浏览器中展现 ...

  2. Asp.Net MVC4.0 官方教程 入门指南之四--添加一个模型

    Asp.Net MVC4.0 官方教程 入门指南之四--添加一个模型 在这一节中,你将添加用于管理数据库中电影的类.这些类是ASP.NET MVC应用程序的模型部分. 你将使用.NET Framewo ...

  3. Asp.Net MVC4.0 官方教程 入门指南之三--添加一个视图

    Asp.Net MVC4.0 官方教程 入门指南之三--添加一个视图 在本节中,您需要修改HelloWorldController类,从而使用视图模板文件,干净优雅的封装生成返回到客户端浏览器HTML ...

  4. Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器

    Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器 MVC概念 MVC的含义是 “模型-视图-控制器”.MVC是一个架构良好并且易于测试和易于维护的开发模式.基于MVC模式的应用程 ...

  5. Android Studio2.0 教程从入门到精通Windows版

    系列教程 Android Studio2.0 教程从入门到精通Windows版 - 安装篇Android Studio2.0 教程从入门到精通Windows版 - 入门篇Android Studio2 ...

  6. Android Studio2.0 教程从入门到精通Windows版 - 入门篇

    http://www.open-open.com/lib/view/open1468121363300.html 本文转自:深度开源(open-open.com)原文标题:Android Studio ...

  7. 零基础快速入门SpringBoot2.0教程 (二)

    一.SpringBoot2.x使用Dev-tool热部署 简介:介绍什么是热部署,使用springboot结合dev-tool工具,快速加载启动应用 官方地址:https://docs.spring. ...

  8. ECMAScript 6.0基础入门教程

    ECMAScript 6.0基础入门教程 转:https://blog.csdn.net/hexinyu_1022/article/details/80778727 https://blog.csdn ...

  9. Android Studio2.0 教程MAC版 -快捷键篇

    本文转至 Android Studio2.0 教程从入门到精通MAC版 - 提高篇 ( OPEN 开发经验库) 第二篇我们开发了一个Hello World应用,并介绍Android Sutdio的界面 ...

随机推荐

  1. DelphiXE10.1自定义控件添加图标方法

    1 在资源文件中加入个24*24的BMP图片,命名为控件的类名(全大写包括T)        2 项目文件中加入对应的 {$R *.dres} 缺省为项目文件同名,自动加入到项目文件(Projrct- ...

  2. 解决vsftpd的refusing to run with writable root inside chroot错误

    参考 http://www.cnblogs.com/CSGrandeur/p/3754126.html 在Ubuntu下用 vsftpd 配置FTP服务器,配置 “ sudo chmod a-w /h ...

  3. Nginx 正向代理

    目前现状:只有1个机器能上网(web),其他机器不能 方法:能上网的做一个代理web服务器中转,其他机器连接它即可.采用nginx Nginx配置如下: server{         resolve ...

  4. Synchronized同步性与可见性

    Synchronized是具有同步性与可见性的,那么什么是同步性与可见性呢? (1)同步性:同步性就是一个事物要么一起成功,要么一起失败,可谓是有福同享有难同当,就像A有10000去银行转5000给身 ...

  5. 如何在Web引用中使用项目自定义的类

    这个是老架构了,不推荐现在这么用,维护一个老项目记录一下. 项目中WebService和客户端是在一个解决方案下,实体类是一个公用的Project,如果使用Web引用自动生成的类会缺少一些实体类定义的 ...

  6. CentOS搭建SVN记录

    1.安装subversion(client and server) $ yum install subversion $ yum install mod_dav_svn 安装成功之后使用 svnser ...

  7. js 继承 对象方法与原型方法

    js函数式编程确实比很多强语言使用灵活得多,今天抽了点时间玩下类与对象方法调用优先级别,顺便回顾下继承 暂时把原型引用写成继承 先看看简单的两个继承 var Parent = function(){} ...

  8. 删除MSSQL中所有表的数据

    CREATE PROCEDURE sp_DeleteAllDataASEXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'EXEC ...

  9. linux 多线程基础

    参考出处:http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html 1.进程与线程 进程是程序代码在系统中的具体实现.进程是拥有所需资 ...

  10. CentOS7 编译安装 Mongodb (实测 笔记 Centos 7.0 + Mongodb 2.6.6)

    环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G,双网卡) 系统版本:CentOS-7.0-1406-x86_64-DVD.iso 安装步骤: 1.准备 1.1 显示系统版 ...