Go NHibernate Tour (2): The first NHibernate program

Source: Internet
Author: User
Tags set set sql server management sql server management studio sql server express

The content of this section

    • Getting Started with NHibernate
    • 1. Get NHibernate
    • 2. Create a database table
    • 3. Create a C # class library project
    • 4. Design Domain
      • 4-1. Design Persistence class
      • 4-2. Writing the mapping file
    • 5. Data Access Layer
      • 5-1. Auxiliary class
      • 5-2. Writing operations
    • 6. Testing of the data access layer
      • 6-1. Configure NHibernate
      • 6-2. Testing
    • Conclusion

Author Note: 2009-11-06 updated

Getting Started with NHibernate

We do it ourselves, step by step to build a nhibernate program to simulate the classic combination of customer/order/product with a real-world scenario of an electronic trading program. Since it is the first time to use NHibernate, our goal is to map a table and finish using NHibernate to read the data, and the following image gives us a first impression. We follow the basic development of the software concept of the process step-by-step completion.

I am using the development environment: Microsoft Visual Studio SP1, SQL Server Express, NHibernate 2.1.1GA.

1. Get NHibernate

Use the Nhibernate-2.1.1.ga version of the official October 31, 2009 release. If you are using NHibernate for the first time, download the latest version of NHibernate (including source code, release version, reference document, API documentation, and choose to download) first. If you use the NHibernate extension project to download here, get the latest version of NHibernate contrib. Nhibernate-2.1.1.ga is the last version of the. NET2.0 platform, please click here for more information about Nhibernate-2.1.1.ga.

Some notes about the NHibernate2.1 version:

NHibernate2.1 version changed the bytecode delay loading mechanism, there are three kinds of 3 kinds of IOC framework dynamic Proxy mode, respectively: Castle frame, Linfu frame, spring.net frame. We just select one, configure the Proxyfactory.factory_class node in the configuration file.

If you use the Castle.dynamicproxy2 dynamic Proxy, reference the NHibernate.ByteCode.Castle.dll assembly and configure the Proxyfactory.factory_class node to <property Name= "Proxyfactory.factory_class" > Nhibernate.bytecode.castle.proxyfactoryfactory,nhibernate.bytecode.castle </property>

If you use Linfu.dynamicproxy dynamic Proxy, reference the NHibernate.ByteCode.LinFu.dll assembly and configure the Proxyfactory.factory_class node to <property name= "Proxyfactory.factory_class" > nhibernate.bytecode.linfu.proxyfactoryfactory,nhibernate.bytecode.linfu</ Property>

If you use the SPRING.AOP dynamic Proxy, reference the NHibernate.ByteCode.Spring.dll assembly and configure the Proxyfactory.factory_class node to <property name= " Proxyfactory.factory_class "> nhibernate.bytecode.spring.proxyfactoryfactory,nhibernate.bytecode.spring</ Property>

In addition NHibernate2.1 requirements. NET2.0 SP1 above version (System.datetimeoffset), please use VS2005, be sure to hit the SP1 patch. It is recommended to use more than VS2008 version.

2. Create a database table

For the first time use, or according to our traditional database table configuration.

Open SQL Server Management Studio Express and create a new database nhibernatesample, creating four tables: Customer table, order form, order Product table, Product table, respectively.

3. Create a C # class library project

Because it is our first program, so I did not follow the domain Driver design method of designing this program, according to everyone's conventional ideas to achieve, and later have the opportunity to introduce domain Driver design.

Note Why you create a C # class library project? In the present software design, most of them are designed by multi-layer architecture, compared with the classic three-tier Architecture (page presentation layer, business logic layer, data access layer), the business logic layer and the data access layer are usually designed using the class library, and the page presentation layer is designed by the Web application. It references the business logic layer and the data Access Layer class library DLL assemblies.

Use VS2008 to create a project for the C # class library named Nhibernatesample. Open the project folder, create a new Sharedlibs folder on its project file directory, and copy the downloaded NHibernate related assembly files to the Sharedlibs folder. For example, here I choose Castle Framework Dynamic Agent:

Create the project with the following structure:

    • Domain (domain model): For persistence classes and O/R mapping operations
    • Data Access layer: Define CRUD operations for objects
    • Data.test (data access Layer testing): Testing the data access layer, where I use the NUnit Unit test framework
    • Web:web page (not implemented in this article, please refer to my blog for other articles)
Project References
  • Domain: Reference Iesi.Collections.dll Assembly (set set in this assembly) and Castle dynamic Proxy
  • Data: Referencing NHibernate.dll and Iesi.Collections.dll assemblies and dynamic agent-related assemblies, domain reference
  • Data.test: Referencing NHibernate.dll and Iesi.Collections.dll assemblies, Nunit.framework.dll Assembly (test framework), domain and data references
4. Design domain4-1. Writing Persistence classes

By simple tradition. NET object (Pocos,plain old CLR Objects (Plain ordinary CLR Objects)) model requires persistence classes when programming. In NHibernate, Poco accesses data through the property mechanism of. NET, which can be mapped to a database table.

Now write a persisted class for the customer to map to the database table. Create a new Customer.cs class file:

namespace nhibernatesample.domain.entities{public    class Customer    {public        virtual int Id {get; set;}        Public virtual string FirstName {get; set;}        Public virtual string LastName {get; set;}}}    
Rules
  • NHibernate uses the getter and setter of attributes to achieve persistence.
  • Properties can be set to public, internal, protected, protected internal, or private
Note NHibernate uses the proxy feature by default, requiring that the persisted class is not sealed, and that its public methods, properties, and events are declared as virtual. In this case, the field in the class is set to virtual, otherwise "Failed:NHibernate.InvalidProxyTypeException:The following types May is not used as Proxies:n HibernateSample.Domain.Entities.Customer:method get_id should be Virtual,method set_id should is virtual "exception. 4-2. Writing the mapping file Tip We want to add the ability to write NHibernate profile smart hints for Microsoft Visual Studio 2008. Just find the configuration.xsd and nhibernate-mapping.xsd two files in the downloaded nhibernate and copy them to X:\Program Files\Microsoft Visual Studio 9.0\ Xml\schemas directory.

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"? >   namespace= "NHibernateSample.Domain.Entities" >    <class name = " Customer ">    <id name=" id "column =" CustomerId ">      <generator class =" native "/>    </id>    <property name = "FirstName"/>    <property name = "LastName"/>  </class></ Hibernate-mapping>
Note The default build action for the XML file is "content," which needs to be modified to "embedded Resource" builds, because NHibernate is looking at the assembly using. NET Reflector by locating the resource file mapping entities in the assembly:

Otherwise the "Failed:NHibernate.MappingException:No persister for:NHibernateSample.Domain.Entities.Customer" exception appears. 5. Writing the data access Layer 5-1. Helper Classes

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 nhibernatehelper{    private isessionfactory _sessionfactory;    Public Nhibernatehelper ()    {        _sessionfactory = Getsessionfactory ();    }    Private Isessionfactory getsessionfactory ()    {        return (new Configuration ()). Configure (). Buildsessionfactory ();    }    Public ISession getsession ()    {        return _sessionfactory.opensession ();    }}
5-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);}
6. Writing tests for the data access layer 6-1. Configuring 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.

<?xml version= "1.0" encoding= "Utf-8"? >
 
   
   Note that the default "copy to Output directory" of the XML file is "Do not copy", which needs to be modified to "always copy". Otherwise, the failed:NHibernate.Cfg.HibernateConfigException:An exception occurred during configuration of persistence layer appears. ----> System.IO.FileNotFoundException: File not Found "nhibernatesample\nhibernatesample.data.test\bin\debug\ Hibernate.cfg.xml "" Exception. 
  
 6-2. Testing

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.

[Testfixture]public class nhibernatesamplefixture{    private nhibernatesample _sample;    [Testfixturesetup]    public void Testfixturesetup ()    {        _sample = new Nhibernatesample ();    }    [Test]    public void Getcustomerbyidtest ()    {        var tempcutomer = new Customer {FirstName = "Li", LastName = "Yong Jing"};        _sample. CreateCustomer (Tempcutomer);        Customer customer = _sample. Getcustomerbyid (1);        int customerId = customer. Id;        Assert.AreEqual (1,customerid);    }}

We use TestDriven.NET to test this method: OK, test pass. Here I use NHibernate monitor NHibernate Profiler to see the results:

Go NHibernate Tour (2): The first NHibernate program

Related Article

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.