Nhib.pdf Quick Guide

Source: Internet
Author: User
Tags log4net

What isNhib.pdf

Nhib.pdf is A. Net-based object persistence class library for relational databases. Nhibernate comes from an excellent Java-based hibernate relational persistence tool.

Nhib.pdf persists your. Net object to a relational database from the bottom layer of the database. Nhib.pdf handles this for you, far better than you have to write SQL statements to access objects from the database. Your code is only associated with objects. nhibernat automatically generates SQL statements and ensures that the objects are submitted to the correct tables and fields.

Why write this guide?

Anyone familiar with hibernate will find that this guide is very similar to Glen Smith's a Hitchhiker's Guide to hibernate. The content here is based on his guide, so all thanks should be given to him.

Not every nhib.pdf document is consistent with the hibernate document. However, similar projects should allow readers to read hibernate documents to better understand how Nhibernate works.

This document is intended to allow you to start using nhib.pdf as quickly as possible. It will show you how to persist a simple object to a table. For more complex examples, refer to nunit testing and additional code.

Development Process

In the future, nhib.pdf will provide some tools to help you automatically generate schema files (still based on Code) or generate classes through ing files (in the funding phase) or update the schema (recommended by a new developer ). However, our example here assumes that everything comes from full handwriting, including setting tables and writing. Net classes. We will perform the following steps.

1. Create a table for persistence. Net objects

2. Construct A. Net class to be persisted

3. Build a ing file that allows nhib.pdf To Know How To persist object attributes.

4. Build a configuration file that allows Nhibernate to know how to connect to the database]

5. Use APIs of nhib.pdf

Step 1: WriteSQL

Here we will use a very simple example. Suppose you are developing a basic user management subsystem for your website. We will use the following User table (assuming you have already set up a database-in the example I call it nhib.pdf ).

               
use NHibernate
go
 
CREATE TABLE users (
  LogonID nvarchar(20) NOT NULL default '0',
  Name nvarchar(40) default NULL,
  Password nvarchar(20) default NULL,
  EmailAddress nvarchar(40) default NULL,
  LastLogon datetime default NULL,
  PRIMARY KEY  (LogonID)
)
go

I am using ms SQL Server 2000, but can also use any database, as long as you have a. Net-based data provider driver for them. We will get a table containing logonid, name, password, email, and lastlogon. After the above standard steps, we will write a. Net class to process a given user object.

Step 2:Generate. NetClass File

When there are a bunch of user objects in the memory, we need some objects to save them. Nhib.pdf works through reflection of object attributes, so we need to add the object attributes we want to persist. A class that can be persisted by nhib.pdf should look like the following:

               
using System;
 
namespace NHibernate.Demo.QuickStart
{
        public class User
        {
               private string id;
               private string userName;
               private string password;
               private string emailAddress;
               private DateTime lastLogon;
 
 
               public User()
               {
               }
 
               public string Id 
               {
                       get { return id; }
                       set { id = value; }
               }
 
               public string UserName 
               {
                       get { return userName; }
                       set { userName = value; }
               }
 
               public string Password 
               {
                       get { return password; }
                       set { password = value; }
               }
 
               public string EmailAddress 
               {
                       get { return emailAddress; }
                       set { emailAddress = value; }
               }
 
               public DateTime LastLogon 
               {
                       get { return lastLogon; }
                       set { lastLogon = value; }
               }
               
        }
}

In the above example, our attributes and building functions are public, but this is not necessary for nhib.pdf. It can use public, protected, internal, or even private for data persistence.

Step 3: Write the ing File

Now we have a data table and the. NET class that needs to be mapped to it. We need a way to let Nhibernate know how to map from one to another. This task depends on the ing file. The easiest way to manage is to write a ing file for each class, if you name it yourobject. HBM. XML and put it in the same directory as the class, nhiberante will make things simple. The following is an example of user. HBM. xml:

               
<?xml version="1.0" encoding="utf-8" ?>
        <class name="NHibernate.Examples.QuickStart.User, NHibernate.Examples" table="users">
               <id name="Id" column="LogonId" type="String" length="20"> 
                       <generator class="assigned" /> 
               </id> 
               <property name="UserName" column= "Name" type="String" length="40"/> 
               <property name="Password" type="String" length="20"/> 
               <property name="EmailAddress" type="String" length="40"/>
               <property name="LastLogon" type="DateTime"/>
        </class>
 
               

Let's take a look at some lines that interest us in this file. The first interesting label is class. Here, we will map the type name (Class Name and Assembly) to the user table in our database, which is a little different from hibernate. You will have to tell Nhibernate where to extract the object. In this example, we install accessoriesNHibernate.ExamplesLoading classNHibernate.Examples.QuickStart.User NHibernate Follow and.Net FrameworkLoad types using the same rules. Therefore, if you are confused about how to specify the type, see.Net Framework SDK

Let's skipidLabel to discusspropertyLabel. After a brief look, you will findNHibernateThe work to be done.nameThe attribute value is exactly ours..Net Class attributes,columnAttribute values are fields in our database.typeThe property is optional (if you do not specify it,NHibernateWe will use reflection for the best estimation ).

Okay, let's go back to the tagid, You can guess that this label will be the primary key mapped to the database table,idTag composition and what we just sawpropertyLabels are similar. The fields mapped to the target database.

Embeddedgenerator Tag notificationNHibernate How to generate a primary key (it will generate a primary key for you, regardless of the type you specify, but you must tell it ). In our example, we setassigned,This means that our object will generate its own primary key (after allUserAn object often needsUserID). If you wantNHiberanteGenerate a primary key for you. You are interested in settinguuid.hexAnduuid.string(Obtain more information from the document)

Tip: If you use Visual Studio. NET for compilation, set the build action attribute of user. HBM. XML to embedded resource. The ing file will be part of the Assembly. More detailed details will be highlighted later.

Tip: If you only change the ing file, you should rebuild the project instead of using build. Visual Studio. NET does not recompile the changed ing file.

Step 4: generate a configuration file for your database

We have not yet told Nhibernate where to connect to the database. The most direct way is to set a Nhibernate configuration section in the configuration file of your application. This is equivalent to using attribute files in hibernate. The configuration is as follows:

               
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
        <configSections>
               <section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </configSections>
        
        <nhibernate>
               <add 
                       key="hibernate.connection.provider"          
                       value="NHibernate.Connection.DriverConnectionProvider" 
               />
               <add 
                       key="hibernate.dialect"                      
                       value="NHibernate.Dialect.MsSql2000Dialect" 
               />
               <add 
                       key="hibernate.connection.driver_class"          
                       value="NHibernate.Driver.SqlClientDriver" 
               />
               <add 
                       key="hibernate.connection.connection_string" 
                       value="Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI" 
               />
        </nhibernate>
</configuration>
               

In the preceding example, the sqlclient driver is used to connect to a database named nhib.pdf locally and provide the user name and password. There are a bunch of attributes that you need to adjust to determine how to allow nhib.pdf to access the database. Again, you can get more information in the document.

Note that the above configuration does not involve log4net configuration information. Nhib.pdf uses log4net to record all internal events. In an application product, in your specific environment, we recommend that you configure log4net and set a certain log level for nhib.pdf.

Step 5: Start to displayNhib.pdfMagic

All the hard work has been completed. You will have the following content

User. CS ---- the persistent C # class

User. HBM. xml ---- your Nhibernate ing File

App. config --- configure the ADO. net connection (you can implement it in code if you want ).

Your database has a user table.

Now you can properly and concisely use nhib.pdf in your code. The simplified version is as follows:

  1. Create a configuration object
  2. Let configuration know what type of objects you will store
  3. Create a session object for the database you selected
  4. Load, save, and query your objects
  5. Submit the object to the database through the flush () method of the session.

To make it clearer, let's look at some code.

First, createConfigurationObject

The configuration object can parse mappings between all. Net objects and the background database.

               
        Configuration cfg = new Configuration();
        cfg.AddAssembly("NHibernate.Examples");
               

The configuration object searches for any files ending with HBM. XML in the Assembly. There are other ways to load the ing file, but this method is the easiest.

Next, createSessionObject

The isession object provides a connection to the background database. The itransaction object provides a transaction that can be managed by nhib.pdf.

               
        ISessionFactory factory = cfg.BuildSessionFactory();
        ISession session = factory.OpenSession();
        ITransaction transaction = session.BeginTransaction();
               

Next, load, save, and query your objects.

Now you can use the traditional. Net Method to manipulate objects. Do you want to save a new object to the database? Try the following method:

               
        User newUser = new User();
        newUser.Id = "joe_cool";
        newUser.UserName = "Joseph Cool";
        newUser.Password = "abc123";
        newUser.EmailAddress = "joe@cool.com";
        newUser.LastLogon = DateTime.Now;
                       
        // Tell NHibernate that this object should be saved
        session.Save(newUser);
 
        // commit all of the changes to the DB and close the ISession
        transaction.Commit();
        session.Close();

As you can see, the important thing about nhiberante is so simple. Continue and query your database to verify the new records in the User table. Now, the important thing is to worry about the business objects and tell nhib.pdf when processing them.

Let's tell you how to get an object when you have a userid (for example, when logging on to your website ). You can open the session in just one sentence and pass in the key.

               
        // open another session to retrieve the just inserted user
        session = factory.OpenSession();
 
        User joeCool = (User)session.Load(typeof(User), "joe_cool");
               

The user object you get is still in the lifecycle! It changes its attributes and persists to the database through flush.

               
        // set Joe Cool's Last Login property
        joeCool.LastLogon = DateTime.Now;
 
        // flush the changes from the Session to the Database
        session.Flush();
               

All you need to do is use nhib.pdf to make the changes you need and call the flush () method of the session to submit the changes. Verify the database and check the changes in "lastlogon" in the record with the user ID "joe_cool.

In addition, you can use system. Collections. ilist to obtain objects from the table. As follows:

               
        IList userList = session.CreateCriteria(typeof(User)).List();
        foreach(User user in userList)
        {
               System.Diagnostics.Debug.WriteLine(user.Id + " last logged in at " + user.LastLogon);
        }
 
This query will return all table records. You often need to do more control, such as getting users logging on from March 14,200 pm, as follows:
               
        IList recentUsers = session.CreateCriteria(typeof(User))
                                      .Add(Expression.Expression.Gt("LastLogon", new DateTime(2004, 03, 14, 20, 0, 0)))
                                      .List();
 
        foreach(User user in recentUsers)
        {
               System.Diagnostics.Debug.WriteLine(user.Id + " last logged in at " + user.LastLogon);
        }
               
 
The document also contains a bunch of robust query methods for you to call. Here, we only give you a certain understanding of the powerful tools provided by nhib.pdf.
        
Finally, the session is called.Close () of the object ()Method To release nhib.pdfAdo. net usedConnect Resources
 
               
        // tell NHibernate to close this Session
        session.Close();
               
 

More specifically...

You have created an object and persisted it and returned it through conditional query or key-value query. I believe you have gained happiness from it.

Now you have a general understanding of nhib.pdf. If you can carefully read a large number of documents from Hibernate 2.0.3, you will get help (the nhib.pdf document is still in its early stages, now it's just a copy of hibernate ).

Enjoy! And happy nhibernating!

Mike doerfler

Again, all rights come from Glen Smith's a Hitchhiker's Guide to hibernate.

Translated by: Jason Xie

Published: 2005-02-24

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.