Powerful ORM tool: nhibloud (iii) Five cores + simple object CRUD + HQL, ormcrud

Source: Internet
Author: User

Powerful ORM tool: nhibloud (iii) Five cores + simple object CRUD + HQL, ormcrud

In the previous two articles, we have a rough understanding of nhib.pdf.

Introduction to ORM: nhib.pdf (1) the role of nhib.pdf solves the conversion problem between objects and databases.

ORM tool: nhib.pdf (2) use CodeSmith to quickly generate ing files and ing classes. Use CodeSmith to export ing classes from tables (usually called Entity) and ing files (tell you how to establish a one-to-one relationship between tables and objects ).


Next, we will perform Demo parsing on the use of NHibernate, which is divided into five parts:

  1. Create a table. To convert an object to a table in the database, you must have a pair of tables. Therefore, you must first create a table in the database that persists the. Net class.
  2. Create class. Create a. Net class. object to be persisted.
  3. Create a ing File. Describes the relationship between objects and libraries and tells NH how to persist the attributes of these classes.
  4. Create the NH configuration fileTo tell NH how to connect to the database and how to connect to different types of databases.
  5. Use APIs provided by NH. Maintain the relationship between objects and databases, CRUD objects and DML databases.

Step details: Part 1: Create a table(The procedure is simple. I will not explain it here)
Part 2: Create a class + Part 3: Create a ing File(This Demo is automatically generated using CodeSmith. For details, see ORM tool: NHibernate (2) use CodeSmith to quickly generate ing files and ing classes.)
Part 4: Create an NH configuration fileIt is mainly used to connect to the database: The driver provider, the driver location, and the database identity authentication information. It is not intended to connect to the database statement that we have previously written, but it is stored in the configuration file. In addition, NH uses a proxy factory to produce different database products, providing better flexibility. If you need to change the SQLServer database to an Oracle database, you only need to change the configuration information.
<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSession> <section name = "hibernate-configuration" type = "nhib.pdf. cfg. configurationSectionHandler, NHibernate "requireParmission =" false "/> </configSession> It doesn't matter if you think the configuration file is complex and hard to remember. NH provides us with a lot of configuration file templates for reference, here we use SQLServer, so you can refer to: Configuration_Templates-MSSQL.cfg.xml


Part 5:Use APIs provided by NH. Maintain the relationship between the object and the database, CRUD the object and DML the database

1. The directory structure is as follows:

1) create a class library Test:

Used to store all objects and. NET ing file (such as Person. cs object, Person. hbm. xml ing file). To enable NHibernate to find all the ing files, you must set it to "embedded resource" to generate Test. dll file backup.

2) Add reference:

2. Add the form Form1 ,:

3. The code in form Form1 is as follows:

First, read the configuration file through config, read all the ing files, and load the Assembly (must be embedded resources)
Second, the session factory is created through SessionFactory, which is responsible for persistent connections and OR ing (the overhead of this object is large, and it is generally recommended to use the singleton mode)
Then, a user-level operation object can be created through session.
Start the transaction object trans = session. BeginTransaction ();


The above idea is similar to the SQL server we have used. Next let's take a look at the differences:

When dealing with databases on layer D, we usually use SQL statements and then operate the database directly. All the operations (add, delete, modify, and query) in NH are for "objects". If you want to save the objects in the database, you need to first convert the object to an SQL statement that the database can recognize. Because all OR ing has been saved in SessionFactory, ISession can implement the SQL statement according to the corresponding dialect.

The following code has implemented simple operation objects. It is mainly implemented through the get, save, and delete methods of the session. Complex queries are complicated. Nhib.pdf provides a powerfulQuery LanguageHQL(Hibernate Query Language). Its syntax is very similar to SQL. The difference is that it can only be used to Query data and cannot be used to add, delete, or modify data. It is fully object-oriented and has the characteristics of inheritance, polymorphism and association.

Using System; using System. collections; using System. collections. generic; using System. windows. forms; using nhib.pdf. cfg; using Test. model; using System. linq; namespace WinFormTest {public partial class Form1: Form {// create session ISession session = null; // create session factory ISessionFactory = null; // create transaction ITransaction trans = null; public Form1 () {InitializeComponent ();} private void Formateload (object sender, EventArgs e) {// read the Configuration file // read all the ing files and load the Assembly, which must be embedded in the resource Configuration config = new Configuration (). addAssembly ("Test. model "); // creates a session factory and is responsible for persistent connections and OR ing. the overhead of this object is large. We recommend that you use the singleton mode to implement factory = config. buildSessionFactory (); // create a user-level operation object session = factory. openSession () ;}// Add User private void btnAdd_Click (object sender, EventArgs e) {// enable transaction object trans = session. beginTransaction (); // Use the existing APIs of nhib.pdf // try {// Object Instantiation method Person p = new Person (); p. name = this.txt Name. text; // Save the object in the database // The object must be converted to an SQL statement that can be recognized by the database // because all OR mappings have been saved in SessionFactory // The ISession can be based on the corresponding dialect implementation SQL statement session. save (p); trans. commit ();} catch (Exception) {// after an error occurs, the transaction rolls back trans. rollback () ;}/// query user private void btnFind_Click (object sender, EventArgs e) {// trans = session. beginTransaction (); // find the person whose ID is 2 // 2 --> ID attribute -- OR --> SQL Where statement Person p = (Person) session. get (typeof (Person), int.Parse(this.txt ID. text); // Console. writeLine (p. toString (); this.txt Name. text = p. name;} // delete user private void btnDelete_Click (object sender, EventArgs e) {try {// start transaction trans = session. beginTransaction (); // find the object Person p = (Person) session based on the provided ID. get (typeof (Person), int.Parse(this.txt ID. text); // Delete the session object. delete (p); tra Ns. commit ();} catch (Exception) {trans. rollback () ;}/// update user private void btnUp_Click (object sender, EventArgs e) {try {// enable transaction trans = session. beginTransaction (); // find the object Person p = (Person) session based on the provided ID. get (typeof (Person), int.Parse(this.txt ID. text); // modify the object property p. name = this.txt Name. text; session. update (p); trans. commit ();} catch (Exception) {trans. rollback () ;}// IQuery interface, which is a private E void btnHQL_Click (object sender, EventArgs e) {// HQL experience -- HQL is the query language for the object // query information of all people // IQuery query = session. createQuery ("from Person"); // IList <Person> persons = query. list <Person> (); // persons. p1 (); // query the information of the person numbered 2 // IQuery query = session. createQuery ("from Person where Id = 3"); // query. list <Person> (). p1 (); // query a person with a letter in the name // session. createQuery ("from Person where Name like '% a % '"). list <Person> (). p1 (); // Session. createQuery ("from Person where t_Name like '% a % '"). list <Person> (). p1 (); // session. createQuery ("from Person where name like '% a % '"). list <Person> (). p1 (); // error // search all // session. createQuery ("select p from Person p "). list <Person> (). p1 (); // session. createQuery ("select * from Person "). list <Person> (). p1 (); // error, no * // query information of persons with a serial number greater than 5 // session. createQuery ("from Person p where p. id> 5 "). list <Person> (). P1 (); // use of Aggregate functions -- count people // session. createQuery ("select count (p. id) from Person p "). list (). p2 (); // Pass Parameter 1 // IQuery query = session. createQuery ("from Person p where p. id>? "); // Query. setParameter (0, 7); // query. list <Person> (). p1 (); // Pass Parameter 2 // IQuery query = session. createQuery ("from Person p where p. id>: id "); // query. setParameter ("id", 7); // query. list <Person> (). p1 (); // Insert data -- Insert/Update/Delete it is not recommended to operate in HQL // IQuery query = session. createQuery ("insert into t_Person (t_Name) values (?) "); // Query. setParameter (0, "kkk"); // query. executeUpdate (); // query data within a specified range -- query the 3-7 records 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} // output of IList <Person> type data, we recommend that you use the C #3.0 extension method to implement public static class ExtraClass {public static void p1 (this IList <Person> p) {// obtain the interface object IEnumerator that can be enumerated <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 provides a detailed explanation through five dimensions: 1. Create a table; 2. Create a class; 3. Create a ing file (how tables and classes correspond ); 4. NH configuration file (connect to the database); 5. Use APIs.

Among them, 2 and 3 we use CodeSmith to automatically generate ing classes and ing files; 4 is the database connection operation we previously performed; 5 through APIS provided by nhib.pdf, through object operations, database operations have been achieved, avoiding lengthy and complex SQL statements.

I hope you will understand the creation process and the use of APIs.





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.