재우니의 블로그

 

 

What is NHibernate:

 

 

ORMs(Object Relational Mapper) are quite popular this days. ORM is a mechanism to map database entities to Class entity objects without writing a code for fetching data and write some SQL queries. It automatically generates SQL Query for us and fetch data behalf on us. 
ORMs(Object Relational Mapper) 은 인기 많듯이, ORM  은 SQL 쿼리를 코드에 기재할 필요없이 database 의 entity 들을 Class Entity 객체로 매핑해주는 매커니즘입니다. 이는 자동적으로 SQL 쿼리를 생성해 주며, 데이터를 가져올 수 있습니다.


NHibernate is also a kind of Object Relational Mapper which is a port of popular Java ORM Hibernate. It provides a framework for mapping an domain model classes to a traditional relational databases. Its give us freedom of writing repetitive ADO.NET code as this will be act as our database layer. Let's get started with NHibernate.

 

NHibernate  또한 인기있는 Java ORM Hibernate 의 하나의 일부분과 동일하게 Object Relational Mapper 의 종류입니다. 이는 하나의 domain model class 들을 일반적인 관계형 데이터베이스를 매핑해주는 프레임워크를 제공해 줍니다. 이는 반복적인 ado.net 코드들을 기재하는 불편함을 해소해주며, 이는 database layer 에서 사용하게 될겁니다.  NHibernate 이 어떤것인지 이제 알아볼까요?

How to download:

There are two ways you can download this ORM. From nuget package and from the source forge site.

ORM 을 다운로드 받을 수 있는 사이트 2개를 제공합니다.

 

  1. Nuget - http://www.nuget.org/packages/NHibernate/
  2. Source Forge-http://sourceforge.net/projects/nhibernate/

Creating a table for CRUD:

I am going to use SQL Server 2012 express edition as a database. Following is a table with four fields Id, First Name, Last name, Designation.

SQL Server 2012 express edition 을 사용할 것이며, 필드명은 First Name, Last name, Designation 으로 합니다. 테이블명은 Employee 입니다.


Creating ASP.NET MVC project for NHibernate:

Let's create a ASP.NET MVC project for NHibernate via click on File-> New Project –> ASP.NET MVC 4 web application.
 File-> New Project –> ASP.NET MVC 4 web application 를 선택합니다.

Installing NuGet package for NHibernate:

I have installed nuget package from Package Manager console via following Command.
Package Manager console 창에서 아래와 같이 명령어를 기재하여 NHIberate 를 설치합니다.


It will install like following.
이제 설치 다 된것을 확인할 수 있습니다.


NHibertnate configuration file:

Nhibernate needs one configuration file for setting database connection and other details. You need to create a file with 'hibernate.cfg.xml' in model Nhibernate folder of your application with following details.

Nhibernate 은 데이터베이스 연결자와 기타 상세한 내역에 대한 환경설정 정보가 필요합니다.

아래와 같이 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">

      Server=(local);database=LocalDatabase;Integrated Security=SSPI;

    </property>

    <property name="dialect">

      NHibernate.Dialect.MsSql2012Dialect

    </property>

  </session-factory>

</hibernate-configuration>

 

Here you have got different settings for NHibernate. You need to selected driver class, connection provider as per your database. If you are using other databases like Orcle or MySQL you will have different configuration. This NHibernate ORM can work with any databases.

 

NHibernate 에 대한 다른 설정들이 있으며, 데이터베이스 연결하는데 있어서 connection provider 와 선택된 드라이버 클래스가 필요합니다. 만약에 Orcle or MySQL 와 같은 다른 데이터베이스를 사용하고자 한다면, 다른 환경을 설정해야 합니다. 참고로 어떤 데이터베이스랑도 NHibernate ORM 와 연동할 수 있습니다.

Creating a model class for NHibernate:

Now it's time to create model class for our CRUD operations. Following is a code for that. Property name is identical to database table columns.

CRUD 를 생성하기 위해 모델 클래스를 만들어 봅시다. 아래와 같이 데이터베이스의 테이블 컬럼들을 프로퍼티 이름으로 기재합니다.

 

 

 

namespace NhibernateMVC.Models

{

    public class Employee

    {

        public virtual int Id { get; set; }

        public virtual string FirstName { get; set; }

        public virtual string LastName { get; set; }

        public virtual string Designation { get; set; }

    }

}

 

Creating a mapping file between class and table:


Now we need a xml mapping file between class and model with name "Employee.hbm.xml" like following in Nhibernate folder.

이제 생성한 클래스와 Employee.hbm.xml 을 가지고 모델을 매핑작업이 필요합니다. 이는 Nhibernate 폴더 하단에 Employee.hbm.xml 파일이 존재합니다.

 

 

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

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

auto-import="true" assembly="NhibernateMVC" namespace="NhibernateMVC.Models">

  <class name="Employee" table="Employee" dynamic-update="true" >

    <cache usage="read-write"/>

    <id name="Id" column="Id" type="int">

      <generator class="native" />

    </id>

    <property name="FirstName" />

    <property name="LastName" />

    <property name="Designation" />

  </class>

</hibernate-mapping>

 

 

 

 

 

Creating a class to open session for NHibernate

I have created a class in models folder called NHIbernateSession and a static function it to open a session for NHibertnate.

모델 폴더에 NHIbernateSession 라는 하나의 클래스를 생성합니다.

 

using System.Web;

using NHibernate;

using NHibernate.Cfg;

   

namespace NhibernateMVC.Models

{

    public class NHibertnateSession

    {

        public static ISession OpenSession()

        {

            var configuration = new Configuration();

            var configurationPath = HttpContext.Current.Server.MapPath

(@"~\Models\Nhibernate\hibernate.cfg.xml");

            configuration.Configure(configurationPath);

            var employeeConfigurationFile = HttpContext.Current.Server.MapPath

(@"~\Models\Nhibernate\Employee.hbm.xml");

            configuration.AddFile(employeeConfigurationFile);

            ISessionFactory sessionFactory = configuration.BuildSessionFactory();

            return sessionFactory.OpenSession();

        }

    }

}

 

Listing:

Now we have our open session method ready its time to write controller code to fetch data from the database. Following is a code for that.

 

 

이제 데이터베이스에서 데이터를 가져 오기 위해 컨트롤러 코드를 작성하는 부분에, open session 메소드를 구현해야 합니다. 코드는 아래와 같습니다.

 

 

using System;

using System.Web.Mvc;

using NHibernate;

using NHibernate.Linq;

using System.Linq;

using NhibernateMVC.Models;

   

namespace NhibernateMVC.Controllers

{

    public class EmployeeController : Controller

    {

   

        public ActionResult Index()

        {

            using (ISession session = NHibertnateSession.OpenSession())

            {

                var employees = session.Query<Employee>().ToList();

                return View(employees);

            }

              

        }

    }

}


Here you can see I have get a session via OpenSession method and then I have queried database for fetching employee database. Let's create a new for this you can create this via right lick on view on above method.We are going to create a strongly typed view for this.

 

여기서 OpenSession 메소드를 통해 세션을 볼 수 있으며, employee database 를 가져오기 위한 데이터베이스를 쿼리를 합니다. 이를 위해, 생성하기 위해, 보기와 같이 마우스 오른쪽 버튼의 클릭을 통해 만들 수 있습니다. strongly typed view 를 생성기를 통해 만들어 보죠.





Our listing screen is ready once you run project it will fetch data as following. 

아래와 같이 데이터를 가져오는 것을 리스트 화면을 출력하는 것을 보실 수 있습니다.



Create/Add:

Now its time to write add employee code. Following is a code I have written for that. Here I have used session.save method to save new employee. First method is for returning a blank view and another method with HttpPost attribute will save the data into the database.

 

이젠 employee code 에 추가하는 부분을 알아보죠. 아래 코드처럼 session.save 메소드를 통해 새로운 employee 객체를 저장하는 것을 보실 수 있습니다. 첫번째 메소드는 blank view 로 반환하며, 또 다른 메소드는 HttpPost 어트리뷰트를 통해 데이터베이스 안에 데이터를 저장합니다.

 

public ActionResult Create()

{

    return View();

}

   

         

[HttpPost]

public ActionResult Create(Employee emplolyee)

{

    try

    {

        using (ISession session = NHibertnateSession.OpenSession())

        {

            using (ITransaction transaction = session.BeginTransaction())

            {

                session.Save(emplolyee);

                transaction.Commit();

            }

        }

   

        return RedirectToAction("Index");

    }

    catch(Exception exception)

    {

        return View();

    }

}


Now let's create a create view strongly typed view via right clicking on view and add view. 

view 에서 우클릭 하여 strongly typed view 를 체크하고 생성합니다.



Once you run this application and click on create new it will load following screen. 

화면에서  create new 를 선택합니다.



Edit/Update:

Now let's create a edit functionality with NHibernate and ASP.NET MVC. For that I have written two action result method once for loading edit view and another for save data. Following is a code for that.

NHibernate 와 ASP.NET MVC 로 수정 기능을 만들어보죠.  첫번째 메소드는 수정할 내용을 로딩해 주기 위한 부분이며, 또 하나는 수정할 데이터를 저장하는 부분입니다.

 

 

public ActionResult Edit(int id)

{

    using (ISession session = NHibertnateSession.OpenSession())

    {

        var employee = session.Get<Employee>(id);

        return View(employee);

    }    

} 

   

[HttpPost]

public ActionResult Edit(int id, Employee employee)

{

    try

    {

        using (ISession session = NHibertnateSession.OpenSession())

        {

            var employeetoUpdate = session.Get<Employee>(id);

   

            employeetoUpdate.Designation = employee.Designation;

            employeetoUpdate.FirstName = employee.FirstName;

            employeetoUpdate.LastName = employee.LastName;

   

            using (ITransaction transaction = session.BeginTransaction())

            {

                session.Save(employeetoUpdate);

                transaction.Commit();

            }

        }

        return RedirectToAction("Index");

    }

    catch

    {

        return View();

    }

}

   


Here in first action result I have fetched existing employee via get method of NHibernate session and in second I have fetched and changed the current employee with update details. You can create view for this via right click –>add view like below. I have created a strongly typed view for edit.
하나의 메소드는 NHibernate session 에서 존재하는 특정 사용자 정보를 가져오는 기능을 주며, 또 하나는 업데이트 할 employee 를 변경해 주는 메소드 입니다. 이를 구현하기 위해 view 에서 우클릭하여 add를 통해 view 를 생성할 수 있습니다.  edit 를 위한 strongly typed view 를 생성해 봅니다.





Once you run code it will look like following.
실행해 보죠.



Details:

Now it's time to create a detail view where user can see the employee detail. I have written following logic for details view.

이제 detail view 를 만들어 보죠. 이는 특정 employee  를 상세히 보여주기 위한 로직입니다.

 

 

public ActionResult Details(int id)

      {

          using (ISession session = NHibertnateSession.OpenSession())

          {

              var employee = session.Get<Employee>(id);

              return View(employee);

          }

      }


You can add view like following via right click on actionresult view.
이 또한 view 에서 add view 를 통해  strongly typed view 를 체크하여 생성합니다. 이름은 Details 입니다. 





now once you run this in browser it will look like following. 

 

Delete:

Now its time to write delete functionality code. Following code I have written for that.

아래 코드는 삭제하는 부분을 기술한 메소드 Delete 입니다.

 

 

public ActionResult Delete(int id)

{

    using (ISession session = NHibertnateSession.OpenSession())

    {

        var employee = session.Get<Employee>(id);

        return View(employee);

    }

}

   

          

[HttpPost]

public ActionResult Delete(int id, Employee employee)

{

    try

    {

        using (ISession session = NHibertnateSession.OpenSession())

        {

            using (ITransaction transaction = session.BeginTransaction())

            {

                session.Delete(employee);

                transaction.Commit();

            }

        }

        return RedirectToAction("Index");

    }

    catch(Exception exception)

    {

        return View();

    }

}


Here in the above first action result will have the delete confirmation view and another will perform actual delete operation with session delete method.
이 또한 하나는 특정 employee  정보를 반환해주는 것과, 또 하나는 삭제하는 부분을 기술한 메소드 입니다.



When you run into the browser it will look like following.
실행해 보면 아래 처럼 특정 employee에 대해 보여주고 아래 Delete 버튼을 호출하면 삭제됩니다.



That's it. It's very easy to have crud operation with NHibernate. Stay tuned for more.

NHibernate 을 가지고 CRUD 기능을 쉽게 만들어 봤습니다.

 

 

펌 : http://www.dotnetjalps.com/2013/09/asp-net-mvc-nhibernate-crud-getting-started.html