MVC中使用Nhibernate

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

NHibernate是一個基於.Net,用於關聯式資料庫的對象持久化類庫.它是著名的Hibernate的.Net版本,NHibernate用於把你的.Net對象持久化到底層的關聯式資料庫中.你完全不用自己編寫Sql語句去操作這些對象,NH會代替你做.你的代碼裡面只需要關心這些對象,NH產生sql語句並能為你取到正確的東西。使用NHibernate的時候可以用任何資料庫,只是在配置Nhiternte的時候配置成相應的資料庫驅動就可以了。

一、準備工作:

1、在資料庫中建立把.Net類持久化的對應表.
2、建立需要被持久化的.Net類.
3、建立對應檔,以告訴NH怎樣持久化這些類的屬性.
4、建立NH的設定檔,以告訴NH怎樣串連資料庫.

步驟1:建立資料庫表
在此執行個體中我使用的是MySql資料庫,建的資料庫名字為CMS,表名為Member;建表語句:

create table member(Id int auto_increment primary key,Account varchar(50) not null comment ‘賬戶‘,`Password` varchar(100) not null comment ‘密碼‘,`Type` int default 0 not null comment ‘類型;0,普通會員‘,`Source` int default 0 not null comment ‘來源;0,普通註冊;1其他註冊‘,Freezed int default 0 not null comment ‘狀態;0,正常;1,禁用‘,`DateTime` datetime not null comment ‘註冊時間‘)comment ‘網站會員‘;

步驟2:建立.Net類:

NH是通過reflection對象的屬性來工作的,所以我們給需要持久化的對象添加屬性.一個對應於上面資料庫結構的類可以寫成這個樣子:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace CMS.Data.DomainModels{    public class Member    {        public virtual int Id { get; set; }public virtual string Account { get; set; }        public virtual string Password { get; set; }        public virtual int Type { get; set; }        public virtual int Source { get; set; }        public virtual int Freezed { get; set; }        public virtual DateTime DateTime { get; set; }    }}

步驟3:編寫對應檔(Mapping File)
現在我們有了資料庫表和.Net類,我們還需要告訴NH怎樣在資料庫和類之間映射.這就需要對應檔了.最簡捷(也是可維護性最好的)方法就是為每一個類編寫一個對應檔,如果你把命名為"XXX.hbm.xml"的對應檔和XXX類檔案放在同一目錄下,NH會很讓 一切變得很輕鬆.這兒,我們的Member.hbm.xml可能會像這樣:

<?xml version="1.0" encoding="utf-8" ?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">  <class name="CMS.Data.DomainModels.Member, CMS.Data" table="Member">    <id name="Id" column="id">      <generator class="native"/>    </id>    <property name ="Account" column="Account"/>    <property name ="Password" column="Password"/>    <property name ="Type" column="Type"/>    <property name ="Source" column="Source"/>    <property name ="Freezed" column="Freezed"/>    <property name ="DateTime" column="DateTime"/>  </class></hibernate-mapping>

下面解釋一下這個對應檔:

第一個tag是class,這裡我們把類型名(類名和Assembly名)映射到資料庫中的member表(這裡和hibernate有些不同,我們必須告訴NH這個類從哪兒來的.這個差異是由.Net和Java Reflect機制的不同引起的).這種情況下,我們是從CMS.Data.DomainModels中載入CMS.Data.DomainModels.Member類.NH遵守.Net Framework使用Reflection載入類型的規則-所以遇到什麼疑惑,就去查查.NET Framework SDK. 讓我們暫時跳過"id" tag,先說property節點."name"屬性值就是我們寫的.Net類中的屬性,column屬性值就是在資料庫中與‘Net類屬性對應的欄位名.type屬性是可選的(如果你沒有標明,NH會給出一個最適合的),但是推薦的做法是帶上這個屬性.hibernate使用者會注意到,在type屬性值裡,我們給出了長度值,這是因為ADO.NET需要這樣做.讓我們返回到"id" tag,你可能會猜想這個tag和映射到表的Primary Key有關.正確.ID  tag的格式和Property tag的相似.我們從Property(name)映射到目標資料庫的欄位(colume).這些嵌入的Generator標記告訴NH怎樣產生Primary Key(NH很方便的就能給你產生一個,不管是什麼類型的,只要你告訴它怎樣去做).

注意:在完成對應檔後,要將該對應檔右鍵->屬性->產生操作的方式改為內嵌資源,

步驟4:建立資料庫設定檔
目前為止,我們還沒有告訴NH到哪兒去找資料庫.最直接的方法就是在你程式的設定檔中給NH一個部分,就是這樣:

   <!-- Nhibernate配置開始 -->  <configSections>    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>  </configSections> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">    <session-factory name="NHibernateSession">      <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>      <property name="connection.connection_string_name">ConnectionString</property>      <property name="show_sql">true</property>      <property name="dialect">NHibernate.Dialect.MySQLDialect</property>      <property name="cache.use_second_level_cache">false</property>      <property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property>      <property name="generate_statistics">true</property>      <property name="cache.default_expiration">300</property>      <property name="cache.region_prefix">CMS</property>      <mapping assembly="CMS.Data"/>    </session-factory>  </hibernate-configuration>  <!-- Nhibernate配置結束 -->

上面的例子中使用MySql驅動,串連到本地的資料庫連結名稱為ConnectionString的資料庫上,映射的檔案在CMS.Data檔案夾下。

以上四個步驟做完後你將會有如下的成果檔案:

1、一個叫做member的資料庫表.

2、Member.cs - 需要持久化的.Net類.

3、Member.hbm.xml - 對應檔.

4、web.config - 帶有NHibernate串連資訊的配置資訊(你也可以在代碼中指定的)

二、開始體驗NHibernate:

在代碼裡面使用NHibernate是很簡單的事情,需要以下步驟:
1、建立一個SessionFactory 對象.

2、建立一個Session串連到設定的資料庫.

3、下面你就可以進行查詢儲存操作了

步驟一、建立一個SessionFactory 對象
在你建立的MVC網站中的某一個Controller裡建立SessionFactory的時候,注意要引入下面兩個引用:

using NHibernate;using NHibernate.Cfg;

建立語句如下:

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

步驟二、建立一個Session對象
ISession對象代表著一個到後端資料庫串連,ITransaction代表一個NHibernate管理的事務(Transaction).

ISession session = sessionFactory.OpenSession();
ITransaction transaction
= session.BeginTransaction();

步驟三、各種操作的應用,現在你可以以.net的方式對待這些對象

如果想在資料庫中儲存一個新的Member只需要

if (session != null)            {                var model = new CMS.Data.DomainModels.Member();                model.Account = "cms";                model.Password = "123456";                model.Type = 0;                model.Source = 0;                model.Freezed = 0;                model.DateTime = System.DateTime.Now;                session.Save(model);                transaction.Commit();                session.Close();            }

整體的Controller代碼如下:

public ActionResult Index()        {            ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();            ISession session = sessionFactory.OpenSession();            ITransaction transaction = session.BeginTransaction();            if (session != null)            {                var model = new CMS.Data.DomainModels.Member();                model.Account = "cms";                model.Password = "123456";                model.Type = 0;                model.Source = 0;                model.Freezed = 0;                model.DateTime = System.DateTime.Now;                session.Save(model);                transaction.Commit();                session.Close();            }            return Content("註冊成功");        }

運行後的結果:

此時在資料庫面會看到剛註冊的該條資料:

在啟動並執行時候可能會出現各種錯誤資訊,一般的錯誤資訊直接在網上搜都可以找到解決方案的

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.