NHibernate Series Learning (i) ORM and NHibernate Getting started instance parsing

Source: Internet
Author: User

Recently, the framework project needs, the data layer wants to use nhibernate, instead of the traditional syntax of SQL statements, more use of object-oriented thinking to maintain the entity and database of this layer of relational mapping (ORM), in the previous exposure to Java when learning to use Hibernate, first to understand the ORM.

What is ORM?

Object-Relational mapping (Object/relation Mapping, or ORM) is a result of the development of object-oriented software development methods. The object-oriented development method is the mainstream development method in the enterprise application development environment, and the relational database is the mainstream data storage system which is stored permanently in the enterprise-level application environment. object and relational data are two representations of business entities, and business entities behave as objects in memory and behave as relational data in the database. There are associations and inheritance relationships between objects in memory, and in a database, relational data cannot directly express many-to-many associations and inheritance relationships. Therefore, object-relational mapping (ORM) system usually exists in the form of middleware, which mainly realizes the mapping of program object to relational database data.

The letter O originates from "object", and R is derived from "relationship" (relational). In almost all programs, there are objects and relational databases. In the business logic layer and the user interface layer, we are object-oriented. When the object information changes, we need to keep the object's information in the relational database.



NHibernate is the implementation of hibernate in the. NET environment. There is little difference between the function and the purpose. In the implementation of the mechanism, NHibernate frequently use C # 's new syntax phenomenon--LAMDA expression, so its use looks a bit strange, no hibernate concise.


What's that? NHibernate?

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.



In today's enterprise environment, using object-oriented software with relational databases can be cumbersome and time-consuming. NHibernate not only manages the. NET class-to-database table mappings (including. NET data types to SQL data type mappings), but also provides methods for querying data and fetching data, dramatically reducing the time it takes to manually use SQL and ADO to process data during development.

The goal of NHibernate is primarily for programming tasks related to data persistence, freeing developers from the writing of the original tedious SQL statements, freeing the developer to invest in the implementation of the business logic. For data-centric programs, developers often use stored procedures in a database to implement business logic, in which case nhibernate may not be the best solution, but for middle-tier applications that are based on. NET and are able to implement the OO business model and business logic. NHibernate is the most useful. NHibernate can help users eliminate or package SQL code for specific vendors and help users transform the result set from a tabular representation into a series of objects.


differs from previous write code to improve

If you open your recent program (for example, PetShop4.0) and look at the DAL (Database access Layer) code, you will certainly see a lot of approximate generic patterns. As an example of how to save an object, you pass in an object, add SqlParameter to the SqlCommand object, correspond all the properties and objects, set the CommandText property of the SqlCommand to the stored procedure, and then run SqlCommand. Write the code repeatedly for each object. Besides, is there a better way? There, introduce a O/R Mapping. Essentially, an O/R mapping will generate a DAL for you. Instead of writing the DAL code yourself, use the O/R Mapping. You use O/R mapping to save, delete, read objects, O/R mapping is responsible for generating SQL, you just need to care about the object just fine.




Step one: Build the Entity object product


<span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;namespace Domain{//<        Summary>///goods//</summary> public class Product {//<summary>///ID        </summary>//Public virtual Guid ID {get; set;}        <summary>///number//</summary> public virtual string code {get; set;}        <summary>/////</summary> public virtual string name {get; set;}        <summary>//Specifications///</summary> public virtual string QuantityPerUnit {get; set;}        <summary>/////</summary> public virtual string unit {get; set;}        <summary>///Price//</summary> public virtual decimal Sellprice {get; set;} <summary>///Price//</summary> public virtual decimal Buyprice {get; set;}    <summary>///remarks///</summary> public virtual string Remark {get; set;} }}</span>

2, create a new XML file with the same name as the entity object under the same project (same directory) as the product object, with ". Hbm.xml" as the extension. such as: Product.hbm.xml
<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? >

Here's the assembly and Namespace properties.

Assembly: The name of the collection, if there are many entity objects under a project, we only need to specify this property, and in the Web. config, include the following: "<mapping assembly=" Domain "/>" on the line.
Namespace: namespace, if this attribute is set, the name of class is as long as it is specified with the same name as the entity object.

It is also important to note that 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. This XML file is then packaged in to generate the class library DLL file, and the name is automatically modified to "Product.hbm.xml".


3. Configuration in Web. config


<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"?><!--This template is written to work with NHibernate.Test.Copy the Te Mplate to your Nhibernate.test project folder and rename it in Hibernate.cfg.xml and change it for your own use before COM Pile tests in visualstudio.--><!--the "The System.Data.dll provider for SQL Server-->

4. New Iproductdao Operation class


<span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;using Domain;namespace Dao{ Public    Interface Iproductdao    {        Object Save (Product entity);        void Update (Product entity);        void Delete (Product entity);        Product Get (object ID);        Product Load (object ID);        Ilist<product> Loadall ();    }} </span>


5, Productdao
<span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;using NHibernate;using Nhibernate.linq;namespace dao{public class Productdao:iproductdao {private Isessionfactory sessionfactory            ; The default is to find the configuration file from App.config,web.config or hibernate.cfg.xml;//var cfg = new NHibernate.Cfg.Configuration ().             Configure (); If the profile is not above "app.config,web.config or hibernate.cfg.xml", it is a custom profile name,////Note that when you use MSTest for unit testing, write the absolute path to the configuration file, or you may not find to;////var cfg = new NHibernate.Cfg.Configuration ().             Configure ("D:/projectstudytest/nhibernate/nhibernatestudy/lesson3.dao/config/hibernate.cfg.xml");            If the user NUnit the unit test, write the relative path. var cfg = new NHibernate.Cfg.Configuration ().             Configure ("Config/hibernate.cfg.xml"); Sessionfactory = cfg.        Buildsessionfactory (); Public Productdao () {//load var cfg = new NHibernate.Cfg.Configuration().            Configure ("Config/hibernate.cfg.xml"); Sessionfactory = cfg.        Buildsessionfactory (); } public Object Save (domain.product entity) {using (ISession session = Sessionfactory.opensessio N ()) {var id = session.                Save (entity); Session.                Flush ();            return ID; }} public void Update (domain.product entity) {using (ISession session = SESSIONFACTORY.O Pensession ()) {session.                Update (entity); Session.            Flush (); }} public void Delete (domain.product entity) {using (ISession session = SESSIONFACTORY.O Pensession ()) {session.                Delete (entity); Session.            Flush (); }} public Domain.product Get (object ID) {using (ISession session = Sessionfactory.opense Ssion ()) {return session. Get&lT;domain.            Product> (ID); }} public Domain.product Load (object ID) {using (ISession session = Sessionfactory.opens Ession ()) {return session.            Load<domain.product> (ID); }} public ilist<domain.product> Loadall () {using (ISession session = Sessionfactor Y.opensession ()) {return session. Query<domain.product> ().            ToList (); }}}}</span>


7. Productdaotest Test class


<span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;using NUnit.Framework;using        Dao;namespace nhibernatetest{[testfixture] public class Productdaotest {private Iproductdao Productdao;        [SetUp] public void Init () {Productdao = new Productdao ();                } [Test] public void savetest () {var product = new Domain.product {                ID = Guid.NewGuid (), Buyprice = 10M, Code = "ABC123", Name = "Computer",            QuantityPerUnit = "20x1", Sellprice = 11M, unit = "Taiwan"};            var obj = this.productDao.Save (product);        Assert.notnull (obj); } [Test] public void updatetest () {var product = This.productDao.LoadAll ().            FirstOrDefault ();            Assert.notnull (product); Product. Sellprice = 12M; Assert.AreEqual (12M, product.        Sellprice); } [Test] public void deletetest () {var product = This.productDao.LoadAll ().            FirstOrDefault ();            Assert.notnull (product);            var id = product.id;            This.productDao.Delete (product);        Assert.null (This.productDao.Get (id)); } [Test] public void gettest () {var product = This.productDao.LoadAll ().            FirstOrDefault ();            Assert.notnull (product);            var id = product.id;        Assert.notnull (This.productDao.Get (id)); } [Test] public void LoadTest () {var product = This.productDao.LoadAll ().            FirstOrDefault ();            Assert.notnull (product);            var id = product.id;        Assert.notnull (This.productDao.Get (id)); } [Test] public void loadalltest () {var count = This.productDao.LoadAll ().            Count; Assert.true (cOunt > 0); }}}</span>

To begin unit testing with NUnit






The following in the database, has helped us to automatically create the completion:





Advantages

(1). Object-oriented: The use of nhiberante only need to manipulate objects, so that the development of more object, abandoned the idea of the database center, a complete object-oriented thinking.

(2). Transparent persistence: A single-threaded object with a persistent state with a business function that has a short lifetime. These objects may be ordinary Poco, this object does not implement a third-party framework or interface, the only special is that they are associated with (just one) session. Once this session is closed, the objects are left out of the persistence state, which can be used freely by any layer of the application. (for example, as a data transfer object that deals with the presentation layer.) )

(3). It is not intrusive, that is, the so-called lightweight framework. Because it has the advantage of transparent persistence, it is not intrusive, it is a lightweight framework. A constant frame is heavyweight, or lightweight, and is based on its intrusive nature. And NHibernate is a lightweight ORM framework.

(4). Better portability: supports multiple databases and facilitates the migration of databases.

(5). Caching mechanism: provides secondary cache and query cache.

(6). Development efficiency: It is well known that the use of nhibernate can simplify the development of the program, so as to achieve rapid development. As a software company, the key to project management is to control development costs. Because the amount of code written after using NHibernate has been reduced, the cost is reduced relative to the previous project cycle with the "SqlHelper, DAL, BLL" development program.



After the net development model, we should try to use object-oriented thinking development, so that the later maintenance costs greatly reduced


(Next, you'll use a set of small and medium-sized enterprise system development platforms, such as nsprint+nhibernate+nstructs+wcf+windows+silverlight+, using NET in your spare time.)

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.