NHibernate Learning Series One

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.

Advantages:

(1) NHibernate not only manages. 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.

(2) 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.

(3) Transparent persistence: 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.

Disadvantages:

(1) Memory consumption: Direct use of "SqlHelper, DAL, BLL" is undoubtedly the most memory-saving. With NHibernate, there is no doubt that the memory overhead is quite large.

(2) Batch database processing: Because NHibernate is an object-oriented ORM framework, the way the database is processed is for a single object. The increase, deletion and modification of the database are positive for a record. For batch modification, delete data, not suitable for nhiberante. This is also a weakness of all or frameworks.

(3) It is not appropriate to use Nhiberante when the table relationship is confused. NHibernate is only appropriate in environments where tables and tables have a relatively clear relationship. If the foreign key should be established, the foreign key is not established. At this point, the use of Nhiberante not only reduces workload, but increases the workload.

Use Nhiberante to make a simple example:

(1) Add a reference assembly:

(2) Write a persistence class:

public class Classes {public Classes () {} #region Classes property defines private int _cid; <summary>///class table ID///</summary> public virtual int CID {g            ET {return _cid;            } set {_cid = value;        }} private string _cname;             <summary>///class name///</summary> public virtual string CName {get            {return _cname;            } set {_cname = value;        }} private int _ccount;            <summary>///class number///</summary> public virtual int Ccount {get            {return _ccount;            } set {_ccount = value; }} private string _cimg;       <summary>///Class logo image///</summary> public virtual string CIMG {            get {return _cimg;            } set {_cimg = value;        }} private bool _cisdel;            <summary>///delete flag///</summary> public virtual bool Cisdel {get            {return _cisdel;            } set {_cisdel = value;        }} private DateTime _caddtime;            <summary>///input time///</summary> public virtual DateTime Caddtime {            get {return _caddtime;            } set {_caddtime = value; }} #endregion}

NHibernate does not impose any restrictions on the type used by the property. All of them. Net types and primitive types (such as String,char and datetime) can be mapped and also include classes in. NET collections (System.Collections). You can map them into values, collections of values, or associated with other entity classes. The ID is a special attribute that represents the database identifier (primary key) for this class. To make the above mentioned runtime class enhancements take effect, all public properties of the NHibernate persistence class must be declared as virtual.

(3) to write an XML file mapping: The XML file must be named in the "class name. Hbm.xml" format; To create a solution folder put the file as follows, the XML will be written with smart hints:

<?xml version="1.0"encoding="Utf-8"? >"urn:nhibernate-mapping-2.2" namespace="Heimanh"assembly="Heimanh"> <className="Heimanh.classes,heimanh"table="Classes"> <id name="CID"column="CID"Type="Int32"> <generatorclass="Identity"/> </id> <property name="CName"column="CName"Type="String"Length=" -"/> <property name="Ccount"column="Ccount"Type="Int32"Length="4"/> <property name="CImg"column="CImg"Type="String"Length=" +"/> <property name="Cisdel"column="Cisdel"Type="Boolean"Length="1"/> <property name="Caddtime"column="Caddtime"Type="DateTime"Length="8"/> </class>

(4) using the NHibernate isession ( persistence Manager), we access the data from the database via the isession

 protected voidPage_Load (Objectsender, EventArgs e) {            //1. Creating a session factory (which can be shared and used, is thread-safe)Isessionfactory factory =NewConfiguration (). Configure ().            Buildsessionfactory (); //2. Create a session (non-shared use, non-thread safe, but if you create a session for each database operation in the current request, it is extremely wasteful, so it is best to create only one session per request)ISession Sess =Factory.            Opensession (); //HttpContext.Current.Items.Add ("Nfsession", Sess); //3. Create a Query object (hql-hibernate query language)IQuery query = Sess. CreateQuery ("From Classes C where C.cisdel = False"); //3.2 More object-oriented query methods//Icriteria crit = Sess.            Createcriteria (typeof (Classes)); //Crit.            ADD (Restrictions.eq ("Cisdel", false)); //Crit.            ADD (Restrictions.eq ("CName", "Andy Lau 2")); //ilist<classes> list = Crit.            List<classes> (); //4. Get query Resultsilist<classes> list = query. List<classes>(); Rptlist.datasource=list;        Rptlist.databind (); }


Object state:

Instantaneous (transient)
There is no data in the database that corresponds to it, and more than the scope is garbage collected.
In fact, it is the object that new comes out and has no relation with ISession; Durable (persistent)
There is data in the database corresponding to it, currently associated with the ISession, and the associated ISession is not closed, the thing is not committed: the persistent object state changes, when the transaction commits will affect the database (NHibernate can detect changes); Off-Tube (detached-out of NH management)
The data in the database corresponds with it, but there is no session associated with it, and the state of the NHibernate object is changed, and can not be detected;HQL and CriteriaHQL (Hibernate Query Language)
Object-oriented query language, unlike SQL, object names in HQL are case-sensitive (except for C # classes and other parts of attributes that are not case sensitive);
HQL is an object rather than a table, and supports polymorphism;
HQL is mainly done by query, the way query is created:
IQuery q = Sess. CreateQuery (HQL);
From person
From User u where u.name=:name
From User u where u.name=:name and U.birthday<:birthday Criteria
Criteria is a more object-oriented query method than HQL;
Icriteria crit = Sess. Createcriteria (typeof (User));
Simple attribute conditions such as: Crit. ADD (Restrictions.eq (Proname,value));
Crit. ADD (Restrictions.eqproperty (proname,otherproname));

Associating mappings using NHibernate

(1) Many-to-one (student-classes) (2)-to-Many (classes-student) (3)-to-Many (Student-idcard) (4) Multiple-to-Multiple (Student-subject) (5) Set mappings (set, List, Map, Bag) (6) Cascading: Cascade (classes-student)

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.