My trip to NHibernate (a): NHibernate five-part song

Source: Internet
Author: User

NHibernate is an object/relational database mapping tool for the. NET environment. The term object/relational database mapping (Object/relational mapping,orm) represents a technique used to map objects represented by object models to SQL-based relational model data structures. -- Baidu Encyclopedia



Brief introduction

        Find the following picture from the Internet, and think this picture is quite good:


        Simple ORM, can achieve such an effect: we do not have to know the contents of the database (R), the system based on M, Access to the database is done automatically by manipulating the object (O). For example, to complete the "Query by ID", we use Get<customer> (customerId) for the object, and this is the SQL statement that is done: SELECT * from Customer where [email  Protected]

        It's obvious that it's the most intuitive representation of these two points:

    • "decoupling": When writing code, we don't have to do with data, we don't have to write SQL statements.
    • oo: More in line with the idea of the object, the operation of the table into the operation of the object.

For NHibernate, there is a comment on the Internet:
What is elegance? The dynamic setting, avoids hardcode, is graceful, the level is clear, the level is the lowest coupling, is elegant, writes only one place, everywhere quotes, is graceful; Code refining, avoid over-design, is elegant, interface clear, simple invocation, is elegant, easy to debug, easy to test, is elegant ... Elegant design and implementation, in terms of scalability, maintainability, development efficiency, development costs, etc. are the best.
Hibernate is the elegant design, it through the configuration file, the establishment of the entity and database mapping, the dynamic generation of SQL statements, to avoid the hardcode of attribute fields, this is its most essential idea.



Demo structure

This is a brief introduction to ORM. Light says do not practice mouth bashi, below begins our first NHibernate program. let's take a look at this demo from the macro:
description of each layer:
    • Domainmodel (Domain model): For persistence classes and O/R mapping operations
    • DAL (data access Layer): Define CRUD Operations for objects
    • Nunittest: Testing the data access layer, where I use the NUnit Unit test framework
Project references (this program is relatively simple, nhibernate related assemblies, only used Nhibernate.dll):
    • DAL: Referencing NHibernate.dll, and domain
    • Data.test: Referencing NHibernate.dll and Nunit.framework.dll assemblies (test framework), domain and DAL references



Five-part song

Next, this is the focus of this article, through five steps (legendary five) can be completed operations:
    1. In the database, create the. NET class persisted table. (You can automatically create a table by mapping without having to build a table, but you must first build the database)
    2. Create a. To be persisted. NET class.
    3. Create a mapping file that tells NHibernate how to persist the properties of these classes.
    4. Create a nhibernate configuration file to tell NH how to connect to the database.
    5. Use the API provided by NHibernate.


I. Database construction (abbreviated)
ii. Writing persistent classes
Create a new Customer.cs class file:
namespace domainmodel.entities{public    class Customer    {public        virtual int CustomerId {get; set;}        Public virtual String FirstName {get; set;}        Public virtual String LastName {get; set;}}}    
rule : NHibernate uses the getter and setter of the property to achieve persistence.
Note : This entity class is required and must not be a sealed type, and the fields in the class are set to virtual.
Third, write the mapping file
NHibernate want to know how to load and store the persisted class object. This is where the NHibernate mapping file works. The mapping file contains the metadata required for the object/relationship mapping. The metadata contains the declaration of the persisted class and the mapping of the property to the database. The mapping file tells NHibernate which table in the database it should access and which fields in the table are used.
here, I write a mapping file for the Customer.cs class. Create a new XML file named Customer.hbm.xml:
<?xml version= "1.0" encoding= "Utf-8"? >
Tip: We want to add the ability to write NHibernate configuration file Smart hints for Microsoft Visual Studio 2012. Just find the configuration.xsd and nhibernate-mapping.xsd two files in the downloaded nhibernate and copy them to C:\Program files (x86) \microsoft Visual Studio 11.0\xml\schemas directory.
Note:The default build action for the XML file is "content", which needs to be modified to "embedded Resource" generation because nhibernate is mapping entities by locating the resource files in the assembly.
iv. Configuration NHibernate
We can save nhibernate configuration in several ways, specifically later, we use Hibernate.cfg.xml file to configure, but don't worry, this file we can in src\ NHibernate.Config.Templates folder is found, directly copied to the Data.test to modify the configuration information and file output properties can be.

Note: The default "Copy to Output directory" of the XML file is "Do not copy", which needs to be modified to "always copy".
v. Using APIs provided by NHibernate
1) Auxiliary class

We can start nhibernate now. First, we want to get a isession (nhibernate unit of work) from Isessionfactory. Isessionfactory can create and open a new session. A session represents a single-threaded unit operation. Isessionfactory is thread-safe, and many threads can access it at the same time. ISession is not thread-safe, it represents a single operation with the database. ISession open through Isessionfactory, after all the work is done, it needs to be closed. Isessionfactory is usually a thread-safe global object that needs to be instantiated only once. We can use the singleton (Singleton) mode in GoF23 to create isessionfactory in the program. This example I have written a helper class nhibernatehelper for creating isessionfactory and configuring Isessionfactory and opening a new session single-threaded method, This helper class can then be used to create isession in each data manipulation class.

public class sessionmanager{    private isessionfactory _sessionfactory;    Public SessionManager ()    {        _sessionfactory = Getsessionfactory ();    }    Private Isessionfactory getsessionfactory ()    {        return (new Configuration ()). Configure (). Buildsessionfactory ();    }    Public ISession getsession ()    {        return _sessionfactory.opensession ();    }}

2) Writing operations

Create a new class of NHibernateSample.cs in data and write a method Getcustomerid to read the customer information. Before writing the method, we need to initialize the session.

Protected ISession Session {get; set;} Public Nhibernatesample (ISession session) {    session = Session;}

NHibernate has different ways to retrieve objects from the database. The most flexible approach is to use the NHibernate Query Language (HQL), which is based entirely on object-oriented SQL.

public void CreateCustomer (customer customer) {    session.save (customer);    Session.flush ();} Public Customer Getcustomerbyid (int customerId) {    return session.get<customer> (customerId);}

Test

Well, finally we can use our method, A new test class NHibernateSampleFixture.cs is created here to write the test case: Call the Getcustomerid method in the Nhibernatesample class to query the customer for CustomerID 1 in the database, and determine if the ID of the returned customer is 1.



Conclusion

in this chapter, we use NHibernate to construct a most basic project, which does not embody nhibernate more details, only depicts the basic face of nhibernate. Of course the use of nhibernate has a variety of program architectures, which I built according to the general pattern.


Information Download:
NHibernate Information

Blog reference:

"NUnit Detailed use Method"

"NHibernate Map File Configuration description"

Rapid generation of NHibernate mapping files and mapping classes of sharp weapon--codesmith software


My trip to NHibernate (a): NHibernate five-part song

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.