NHibernate I got easier

By Billy Ruiz,2015-05-04 15:43
18 views 0
NHibernate I got easier


    This article from the I try to learn to use Nhiberbnate frustration.I found that if I got all the materials are not so blurred or too detailed introduced.What I need is a simple tutorial directly, can let me for I got familiar as soon as possible.I have never found.Fortunately, this article will meet these requirements.

    The article some long, but I encourage you to read in your way.I got is a complex procedure, it is a long and tortuous the learning process.This article will provide you flattened twists and turns, from a few days or weeks to a few hours.

    The problem

    I got the purpose is to solve the problem of a well-known, object persistent code in the bottleneck problem in the process of development.Many articles showed that a quarter to a third of the program code is about object persistence, reads data from a database, and write the data back to the database.The code is repetitive, time-consuming, and there are many trivial code to write.

    For this problem, there are a lot of solutions are available.Code generation can generate data access code in a few seconds.But if the business model changes, the code needs to be generated.Object relational mapping (ORMs) the use of a new way, as I got.They manage data access more transparent, provides many simple API, you can use a line of code to implement load and save the entire object.

    Introduction to got

    I got is a persistence engine framework.It is loaded from the database business object, and the change of these objects will update in the database.Can be seen from the article above,

    it can only use one or two lines of code to achieve the business object of the loading and saving.

    I got using a mapping file to guide to business objects from the database data conversion.Another way, you can use the features and properties of a class to replace the mapping file.In order to make things as simple as possible, in this article we will use a mapping file, instead of using the class features.In addition, the mapping file can clearly separate the business logic and persistence code.

    Ok, we just need to add a few lines of code in the program, and a persistent class to each mapping file, and I got to take care of all database operations.I don't know how many development using got will save us time.

    Remember that in environment, I got is not the only ORM framework.There are many commercial and open source products can provide such service.I got is one of the most popular, mainly because of his genetic self-improvement large Hibernate, a very popular ORM framework in Java environment.In addition, Microsoft also provides the ADO.NET Entity Framework "", to provide the ORM services.However, this product has been delayed and has been a long time didn't released.

    Install got

    Use I got the first step is to download I got and Log4Net (an open-source logging application, I got to use it to record the error and warning), I got contains the latest version of the Log4Net, you can download the entire Log4Net install package, here is the download address:

    ; NHibernate

    ; Log4Net

    I got Log4Net is not, but its automatic logging during debugging function is very useful.


    In this article, I'll use a simple example program, rather than explain how to use I got for data access.This is a console application, by eliminating the UI code make application easier.This program will create a number of business objects, I got to use to persist to them, then they read from the database.

    In order to program to run, you need to do several things:

    ; Add got to Chen and Log4Net assembly references

    ; To add database program

    ; Change the database connection string

    The example application reference I got and Log4Net.These applications should be your machine recognition, if you got and log4net install in the default directory.If these references are not recognized, you can use I got respectively. The DLL and Log4Net. DLL to replace the reference position.The DLL file can be found I got in the installation directory.

    This sample program is according to the SQL Server Express 2005 to configuration, the database file (NhibernateSimpleDemo. MDF and NhibernateSimpleDemo. LDF) have been packaged in the zip file.You can will be the SQL Server database on your machine.

    Finally, the database connection string configuration in the App. The config file, you are using a SQL Server database by default.You can according to their own versions of SQL Server to the machine, to change the database connection string.

    The business model

    Here there are two ways to use got to create the application.The first is "a data-centric" approach, it begins from data model and create a business object.The second is "object centered" method, from the business model and create a database to persist the model.This sample program using object centered approach.

    The business model in the example here:

    This model shows a ordering system, the framework of this model is not complete, here I got is just used for classes to define object persistence.Obviously the design of this model does not represent best practice, but used to show how I got to work enough to cope with.

    This article will use this model to explain using got several concepts of object persistence.

    ; Simple processing properties

    ; Processing Components

    ; Handle one - to - the things

    ; To deal with things - to - one

    ; To deal with things - to - the things

    This article does not involve advanced topics, such as inheritance.

    This model is composed of five classes, one of the four is to persistent classes, the non-persistent ordersystem class serves as the host of the object model.We will run the program initializes the OrderSystem object, and then we will load other objects to the OrderSystem.

    OrderSystem. Customers attributes have sellers list of Customers, Customers can access through the CustomerID, every Customer object has an ID, name, and address, a sequence of the orders.The address will be folded into a single address class.

    The Order class contains an Order ID, time, customer information, and a lot of purchasing product information.

    Product class contains ID, name.

    Please note that we only pay attention to how I got to work, the program initialization, Product object will be instantiated into the OrderSystem. The Catalog properties, when an Order is created, the Product object references will not be copied to the Order. The OrderItems attribute.

    I got a strong characteristic is no need for the business class implements a special interface.In fact, the business object usually don't have to worry about the persistence mechanism to load and save them.I got to use the map data stored in separate XML files.

    The database

    Database and object model is not completely matching, object model contains an Address class, but not with the matching table in the database.Has an OrderItems table in the database, but the object model and there is no corresponding with the persistence of class.Here does not match and didn't mean it, we want to show I got one of those concepts is here does not need in a database table with class is one-to-one.

    Here is one of the reasons that don't exactly match:

    ; Address class does not represent the business model of an entity, on the contrary, it only represent

    the value of an entity, in this case, for the Customer. The Address attribute, we will Address a

    separate class, so that we can define what I got to use the Component mapping ".

    ; The OrderItems table is a many-to-many relationship of the Orders and Products in connection

    table, so also does not represent an entity in the object model.

    The Customer table contains a skeleton of ordinary Customer information, contains the Address of the Customer information.Best practices will not like us, it will put the Address in a separate table.We put the Address information stored in the Customer table, so that we can explain what is got using 'Components' class, instead of using the Address your own table, we will discuss in the following detailed usage of Components.

    The simplest of the Orders table contains only one order information, only ID, time, and CustomerID.The relationship between the Orders and Customers through a foreign key Orders. UstomerID column corresponding to the Customer. The ID column.

    All orders to be a many-to-many relationship (each Order contains a lot of commodity information, each commodity information is contained in many orders), so we need the OrderItems table as intermediary, simple connection Order number and Product code.

    This database is not a best practice, it contains only information used to show how I got to work.

    Mapping business model

    Introduce many got thestart of the article is based on the configuration file, but from another place: mapping classes.Mapping is the core of the got, and the configuration is for beginners a big stumbling block.Introduce back again when we talk about the map, we got the configuration of the part.

    Mapping simply specify which a table corresponding to which a class.We put the mapping class of the corresponding table is called the "map" of a class.

    We've said in the above, I got no need specific interfaces or specific code written in class to map.But it need to be declared as Virtual, so we can create proxies in time of need.I got the document discusses why so, now we put all the business model into the declaration of a class of Virtual.

    Mapping can be implemented with a separate XML file and can also be done by add features on the class attribute.Be used to map the XML documents can be referenced in any of the project.For simplicity, we will show one way: by XML file mapping, mapping file needs to be compiled into the assembly of the embedded resources.

    You can mapping many classes in the same file, but usually create a mapping file for each class.This mapping file can maintain a short and easy to read.

    Beforestarting our mapping experiment, first let's take a look at the Customer. HBM. XML file.HBM. XML suffix is got a standard mapping file suffix.We put the map files in the Model file, but we can put them in anywhere.The key point is the file of BuildAction attribute is set to Embedden Resource (embedded resources).This setting will compile a mapping file into the assembly, so take them out from the program.

    Mapping file is a standard format:

    <? xml version="1.0" ?>

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

    namespace ="NHibernateSimpleDemo"

    assembly ="NHibernateSimpleDemo" >

    The first tag is the XML declaration, the second tag defines the XML namespace, you can add an XSD information here.The second tag also includes attribute information, defines the mapping file to be used in the assembly name, so that you can help us avoid write all the name of the class in the map tag.

    < class > tag

    Under a label used to identify the we need mapping class:

    <!-- Mappings for class 'Customer' -->

    < class name ="Customer" table ="Customers" lazy ="false" >

    < class > tag attribute specifies the class to map, and its mapping table:

    ; The name attribute specifies the name of the class to map

    ; The table attribute of the specified class mapping table

    ; Told I got lazy attribute for this class without using 'lazy loading'

    'lazy loading' told I got don't load this class objects from a database table, until the program needs to access the object data is loaded.This way can reduce the memory footprint a business object, so as to improve the performance.In simple, we will in this sample program does not use lazy loading.But in the later use when I got to do project, until the early know it thoroughly.

    < class > tag still has a lot of properties, can refer to the help documents I got.

    < id > tag

    We have identified the classes and the corresponding mapping table, then we need to identify the identity of the attributes and map the identity column in the table.When we create the data, we need to identify CustomerID primary key (primary key).

    So to these:

    ; Specify the Customer class identity property

    ; The identity column to specify the Customer table records

    ; Told that I got to SQL Server Settings CustomerID column values

    <!-- Identity mapping -->

    < id name ="ID" >

    < column name =" CustomerID " />

    < generator class ="native" />

    </ id >

    The < generator > tag specifies the database record identity column values generated by the native SQL Server database.

    Simple properties

    We set up the identity of the property, we set up the class next general attributes of the Customer class has a simple attribute: Name.We put it matched with the Name column Customer database table, attribute and column names is the same, so the mapping file is simple:

    <!-- Simple mappings -->

    < property name ="Name" />

    We can match the Name attribute to a different Name column (e.g., CustomerName).

    Component mapping

    Got to mapping using component that there is no corresponding table in the database class to map, as the above mentioned Address class, just as a property value of the Customer, the database without corresponding Address table, it follows a distinction often appear in the "entity" and "value classes".

    ; An entity class represents an entity in the business model, in our business model, entity class is the

    Customer, the Order, and OrderItem.These classes corresponds to a business object.

    ; Address class does not represent a business object, which provides a wrapper class value, in the

    terminology of I got, it is a Customter object of a component.

    I got 'Component' using the word has nothing to do.A Component is an entity object of a value, with no database mapping table.

    <!-- Component mapping: Address -->

    < component name ="Address" >

    < property name ="StreetAddress" />

    < property name ="City" />

    < property name ="State" />

    < property name ="Zip" />

    </ component >

    The < component > tag is a collection.I got to use reflection mechanism to determine its true type, you can also through the class attribute to specify that corresponds to the name of the class.Customer. HBM. XML file will match the two classes.

    Joint mapping

    Object-oriented design based on the business model classes in the interrelated concepts.

    ; One - to - One: an object as to another object.As a husband and a wife.

    ; One - to - many: refers to the container, like a Customer object can contain many Order object.

    ; Many - to - one: Many objects can point to the same object, other like Many Order corresponds to a

    single Customer object.

    ; Many - to - the things that Many objects can be specified any of another object.As an order there

    are a lot of products, a product can be included in a lot of orders.

    Set mapping: One - To - the things

    In the Customer class, you will find that there is a the Orders property, said all the order information of the clients.Need to note is that: the Orders property is not a List < T > type, but IList < T >.

    // Property variable

    private IList < Order > p_Orders = new List < Order > ();

// Orders property

    public IList < Order > Orders


     get { return p_Orders; }

     set { p_Orders = value; }


    The Orders attribute is declared IList < order >, has been instantiated as a List < order >.

    This is because I got to set is declared interfaces, rather than the interface implementation.As said above, the need to be defined as the interface, rather than a specific class.This is considered good programming practice.Definition for the interface, so that I got more flexible, and can improve efficiency.

    I got collection provides several tags to match.Because the current collection is a IList < T >, and now we can use the < bag > to match.

    <!-- One-to-many mapping: Orders -->

    < bag name ="Orders" cascade ="all-delete-orphan" lazy ="false" >

    < key column ="CustomerID" />

    < one-to-many class ="Order" />

    </ bag >

    Name attribute can be specified to match the attributes of a class of cascade attribute set said I got will operate all child objects, including load, save, and delete.All - delete - orphan said I got online save, delete all of the current class corresponding to the object.

    Like: when we delete the Customer this object, attribute the Orders under the Customer all the Order will be deleted.

    Of all the associated map, cascade must specify a value, otherwise I got online will not be saved or deleted.In addition < class > tag can specify a default cascade, use the default - cascade.But this value will only provide to use the online operation in the preservation and update operations, not to delete also use on-line operation.So, still had better set cascade the value of this attribute.

    Same as above, for the sake of simplicity, we still can't use lazy loading.

    The < bag > tag contains two tags:

Report this document

For any questions or suggestions please email