ORM Tool: NHibernate (iii) Five-part + Simple Object crud+hql

Source: Internet
Author: User
Tags static class

In the previous two articles, we have already made a general understanding of NHibernate

ORM: NHibernate (i) Introduction NHibernate: Solve the problem of object and database transformation

ORM: NHibernate (ii) Use the Codesmith to quickly generate mapping files and mapping classes using Codesmith to export the mapping class (which is commonly referred to as entity) and the mapping file (which tells you how the table and the object establish a one by one correspondence).


Next will be the use of NHibernate to do demo analysis, divided into five parts:

    1. Create a table . To convert an object to a table in a database, you naturally have to have a table for one. Therefore, the first thing to do in the database is to create a. NET class persisted table.
    2. create the Class . Create a. To be persisted. NET class. Object.
    3. Create a mapping file . Describes the relationship between objects and libraries and tells NH how to persist the properties of these classes.
    4. Create a NH configuration file that tells NH how to connect to a database and how to connect to different kinds of databases.
    5. use the API provided by NH. Maintains relationships between objects and libraries, crud on objects, and DML against databases.

Step Details: Part I: Creating a table (the steps are simple, not explained here)
Part II: Create a class + third: Create a mapping file (this demo is automatically generated using Codesmith, see theORM Tool: NHibernate (ii) quickly generate mapping files and mapping classes using Codesmith ")
Fourth: Create a NH configuration file       Mainly used to connect the database: The driver's provider, the driver's location, the database authentication information and so on, and we have written the database connection statement unintentionally, but placed in the configuration file only. And NH uses a proxy factory to produce for different database products, providing greater flexibility, if you need to change the SQL Server database to Oracle database, you only need to make changes to the appropriate configuration information.
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSession> <section name= " Hibernate-configuration "type=" Nhibernate.cfg.configurationsectionhandler,nhibernate "requireParmission=" false "/ > </configSession> It doesn't matter if you think the configuration file is complicated and can't be remembered. NH provides us with a number of template templates for reference, here we use SQL Server, so we can refer to:configuration_templates-MSSQL.cfg.xml

Part Fifth: using the API provided by NH . maintains relationships between objects and libraries, crud on objects, and DML on databases

1. The directory structure is as follows:

1) New Class library test:

Used to store all objects and. NET mapping files (such as the Person.cs object here, the Person.hbm.xml mapping file), in order for NHibernate to be able to find all the mapping files, it must be set to " embed resources " to generate Test.dll file fallback.

2) Add Reference:

      1. External references NHibernate and NHibernate.ByteCode.Linfu.
      2. Project Reference Test.dll

2, add the form Form1,:

3. The code in form Form1 is as follows:

First, read the configuration file through config, read all the mapping files, load the assembly (must be an embedded Resource)
Second, create session factory through Sessionfactory, responsible for persistent connection and or mapping (the object is more expensive, it is generally recommended to use singleton mode)
Then, create an action object that can be used at the user level through the session.
Open Transaction Object trans = session. BeginTransaction ();


The idea above and the SQL Server we used to use is a truth. Next look at the difference:

     When we used to deal with databases, we usually use SQL statements and then manipulate the database directly. and All operations in NH (increase and revise) All for" object ", If you want to save the object in the database, you need to first convert the object into an SQL statement that the database can recognize, because all the or mappings have been saved in Sessionfactory, ISession can implement the SQL statement according to the corresponding dialect.

a simple operand has been implemented in the code below. Mainly through the session of GET, save, delete method to achieve. It can be tedious to implement complex queries. NHibernate provides a powerful query language HQL(Hibernate query Language) whose syntax is very similar to SQL, unlike Can only be used to query the data, can not be used for data increment, delete, change. It is completely object-oriented, with inheritance, polymorphism, and correlation features.

Using system;using system.collections;using system.collections.generic;using system.windows.forms;using NHibernate;        Using nhibernate.cfg;using test.model;using system.linq;namespace winformtest{public partial class Form1:form {        Create session ISession session = NULL;        Create Session factory Isessionfactory factory = null;        Create transaction ITransaction trans = null;        Public Form1 () {InitializeComponent (); } private void Form1_Load (object sender, EventArgs e) {//Read config file//Read all mapping files, load assembly, must be nested Into the resource configuration config = new configuration ().            addassembly ("Test.model"); Creating a session factory, which is responsible for persistent connections and or mappings, is a relatively expensive object, and it is generally recommended to implement Factory = config in a singleton mode.            Buildsessionfactory (); Create an Action object that can be used at the user level session = Factory.        Opensession ();  }//Add user private void btnAdd_Click (object sender, EventArgs e) {//Open transaction Object trans = SessioN.begintransaction (); Using NHibernate existing API//experience Process try {//Object instantiation Way Person p = new                Person ();                P.name = This.txtName.Text; Save the object in the database//the object must be converted into a SQL statement that the database can recognize//because all or mappings have been saved in Sessionfactory//isessi On can implement the SQL statement session according to the corresponding dialect.                Save (P);            Trans.commit (); } catch (Exception) {//error, transaction rollback trans.            Rollback (); }}//query user private void Btnfind_click (object sender, EventArgs e) {//trans = Sessi Mnl            BeginTransaction (); Look for the person with ID number 2//2-->id property--or-->sql The WHERE statement for man P = (person) session. Get (typeof (person), Int.            Parse (This.txtID.Text));            Console.WriteLine (P.tostring ());        This.txtName.Text = P.name; }//delete user private void Btndelete_click (objECT sender, EventArgs e) {try {//Open transaction trans = session.                BeginTransaction (); Finds the object by the provided ID, p = (person) session. Get (typeof (person), Int.                Parse (This.txtID.Text)); Object Delete session.                Delete (P);            Trans.commit (); } catch (Exception) {trans.            Rollback ();                }}//update user private void Btnup_click (object sender, EventArgs e) {try { Open transaction trans = session.                BeginTransaction (); Finds the object by the provided ID, p = (person) session. Get (typeof (person), Int.                Parse (This.txtID.Text));                Modify Object Properties P.name = This.txtName.Text; Session.                Update (P);            Trans.commit (); } catch (Exception) {trans.            Rollback (); }        }       IQuery interface, which is for object query private void Btnhql_click (object sender, EventArgs e) {//HQL experience--hql is for The query language of the object//query all information//iquery query = session.            CreateQuery ("from person"); ilist<person> persons = query.            List<person> ();            PERSONS.P1 (); Query the information for the person with number 2//iquery query = session.            CreateQuery ("From person where id=3"); Query.            List<person> (). P1 (); The person with the letter A in the name//session. CreateQuery ("From the person where Name is like '%a% '").            List<person> (). P1 (); Session. CreateQuery ("From the person where the t_name like '%a% '").            List<person> (). P1 (); Session. CreateQuery ("From the person where name is like '%a% '"). List<person> (). p1 ();//error//Find all//session. CreateQuery ("Select p from Person P").            List<person> (). P1 (); Session. CreateQuery ("SELECT * from person"). List<person> (). p1 ();//error, no *//Find number greater than 5People's information//session. CreateQuery ("from person p where p.id>5").            List<person> (). P1 (); The use of aggregate functions-the number of statisticians//session. CreateQuery ("SELECT count (p.id) from Person P").            List (). P2 (); Reference 1//iquery query = session.            CreateQuery ("from person p where p.id>?"); Query.            Setparameter (0,7); Query.            List<person> (). P1 (); Reference 2//iquery query = session.            CreateQuery ("from person p where p.id>:id"); Query.            Setparameter ("id", 7); Query.            List<person> (). P1 (); Inserting data--insert/update/delete is not recommended to operate inside HQL//iquery query = session.            CreateQuery ("INSERT into T_person (t_name) VALUES (?)"); Query.            Setparameter (0, "KKK"); Query.            Executeupdate (); Query the specified range of data--query 第3-7条 record IQuery query = session.            CreateQuery ("from person"); Query. List<person> (). Skip<person> (3). Take<person> (5). Tolist<person> (); ; Using Icriteria to implement this function may be more convenient}//to the output of ilist<person> type data, it is recommended to use the c#3.0 extension method to implement public static class Extracla                SS {public static void P1 (this ilist<person> p) {//Gets an enumerable interface object                Ienumerator<person> ie = P.getenumerator ();                Console.WriteLine ("\ n-----------------------\ n"); Traverse while (ie. MoveNext ()) {Console.WriteLine (ie.                Current.tostring ());            } Console.WriteLine ("\ n-----------------------\ n");                } public static void P2 (this IList p) {IEnumerator ie = p.getenumerator ();                Console.WriteLine ("\ n-----------------------\ n"); while (ie. MoveNext ()) {Console.WriteLine (ie.                Current.tostring ());            } Console.WriteLine ("\ n-----------------------\ n");   }     }    }} 

Summary: for the operation of NHibernate, this article through five parts of the detailed explanation: 1, create a table, 2, create a class, 3, create a mapping file (table and class how to correspond), 4, NH configuration file (Connection database), 5, take advantage of API operation.

Among them, 2, 3 we use Codesmith to automatically generate mapping classes and mapping files, 4 is what we have done to connect the database operations, 5 through the nhibernate provided by the API, through the object operation, has achieved the purpose of manipulating the database, to avoid lengthy and complex SQL statements.

We would like to focus on understanding the process of creation and the use of APIs.


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.