http://nhibernate.sourceforge.net/quickstart.html
NHibernate Quick Guide
What is NHIBERNATE
NHibernate is an object persistence class library based on .NET based on relational databases. NHibernate comes from a very excellent Java-based Hibernate relational persistence tool.
NHibernate persists from the bottom of the database to the relational database. NHibernate has handled these, far better than you have to write SQL to get from data inventory. Your code is just just with an object association, NHibernat automatically generates a SQL statement and make sure that the object is submitted to the correct table and field.
Why write this guide?
Anyone familiar with Hibernate will find this guide and Glen Smith's a hitchhiker's guide to hibernate very similar. The content here is based on his guide, so all the gratitude should give him.
NHibernate's documentation is not all consistent with Hibernate's documentation. However, the similarity of the project should enable the reader to understand how NHibernate works well by reading Hibernate documents.
This document is intended to let you start using NHibernate as fast as possible. It will introduce how to persist a simple object into a table. For more complex examples, you can refer to NUnit testing and accompanying code.
Development process
NHibernate will provide some tools to help you automatically generate a Schema file (currently based on code) or by mapping file generating classes (in the financing phase) or Update Schema (from a new developer's suggestion). However, our example is assumed that everything comes from full handwriting, including settings tables and .NET classes. We will make the following steps.
1. Newly built a table that will last .NET object
2. Build a .NET class that needs to be persisted.
3. Build a mapping file that allows NHibernate to know how to persist object properties
4. Build a profile that let NHIBERNATE know how to connect to the database]
5. Use NHibernate's API
Step 1: Write the SQL of the build table
Here we will use a very simple example. Suppose you are developing a basic user management subsystem for your website. We will use a User table (assuming that you have set a database - in the example I call it NHIBERNATE).
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 you can also use any database as long as you provide a driver based on their .NET data. We will get a table containing Logonid, Name, Password, Email and LastLogon. After the above standard steps, our next step is to write a .NET class to process a given User object.
Step 2: Generate a .NET class file
When there is a plurality of User objects in memory, we need some object to save them. NHibernate works through the reflection of the object properties, so we need to add the object properties we wish to persistent. A class that can be persisted by NHibernate 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 {returna usrname;}
Set {usrname = 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 build functions are public, but this is not necessary for NHibernate. It can use public, protected, internal or even use private to persist data.
Step 3: Write mapping files
Now we have a data sheet and need to map its .NET class. We need a way to let NHibernate know how to map from one to another. This task depends on the mapping file to complete. The most easy management method is to write a mapping file for each class. If you name it is YourObject.hbm.xml and put it in the same directory of the class, NHIBERANTE will make things simply. Below is an example of user.hbm.xml:
XML Version = "1.0" encoding = "UTF-8"?>
id>
hibernate-maping>
Let's take a look at some of this document that makes us interested in some lines. The first interesting label is Class. Here we will map the type name (class name and assembly) to the USER table in our database, where Hibernate has a little bit different. You will have to tell NHibernate where to extract the object. In this example we loaded NHibernate.examples.quickStart.user from the fitting NHibernate.examples. NHibernate follows and .NET Framework the same rules to load types. So if you are somewhat confusing in how you specify a type, please see the .NET Framework SDK.
Let us skip the ID tag first to discuss the Property label. Briefly look at it, you will find the work you have to do. The value of the Name property is the properties of our .NET class, the column property value will be the field in our database. The Type property is optional (if you don't indicate, NHibernate will use the reflection to make the best speculation).
Ok, let's go back to the label ID, you can guess this tag will be the primary key of the map database table, which is true, the composition of the ID tag is similar to the Property label we just watch. We map attributes to fields of the target database.
The embedded Generator tag tells NHibernate how to generate a primary key (it will properly generate the primary key, no matter what type you specify, but you must tell it). In our example, we set it as Assigned, meaning that our object will generate the primary key (after all, the User object often needs a userid). If you manage NHIBERANTE to generate primary keys for you, you are interested in setting UUID.HEX and UUID.String (more information from documentation)
Tip: If you use Visual Studio.net to compile, set the manufacture of user.hbm.xml to Embedded Resource. The mapping file will become part of the assembly. More detailed details will be displayed later.
Tip: If you are just changing the mapping file, you can't use Build and should Rebuild project. Visual Studio.NET does not recompile to change mapping files.
Step 4: Generate a profile for your database
We haven't told NHibernate where we haven't told NHIBERNATE to connect to the database. The most direct way is to set a NHibernate configuration section in your application profile. This is equivalent to using the properties file in Hibernate. The following configuration:
XML Version = "1.0" encoding = "UTF-8"?>
configsections>
Key = "hibernate.connection.provider" Value = "NHibernate.Connection.driverConnectionProvider" /> Key = "hibernate.diaract" Value = "nhibernate.diaract.msql2000diact" /> Key = "hibernate.connection.driver_class" Value = "NHibernate.driver.sqlclientDriver" /> Key = "hibernate.connection.connection_string" Value = "Server = localhost; initial catalog = nhibernate; integrated security = sspi" /> NHibernate> configure> The above example uses SQLClient drivers to provide the username and password. There is a bunch of properties you need to adjust to determine how NHibernate to access the database. Once again, you can get more information in your document. Note that there is no configuration information to log4net in the above configuration. NHibernate uses log4net to record everything that happens inside. In an application product, in your specific environment, I recommend configuring log4net and set a certain log level for NHibernate. Step 5: Beginning the magic of NHibernate All hard work has been completed. You will have the following User.cs ---- You need a persistent C # class User.hbm.xml ---- your NHibernate mapping file App.config - The configuration information connected to the ADO.NET (if you want, you can implement it in the code). There is a USER table in your database. Now you can use NHibernate in your code. The simplified version is as follows Create a Configuration object to let Configuration know that you will store what type of objects creates a session object on your choice. Subsenos. In order to make you clearer, let's see some code. First, create a Configuration object The Configuration object is able to parse all .NET objects and mapping relationships in the background database. Configuration CFG = New Configuration (); Cfg.addassembly ("NHibernate.examples"); The Configuration object will search any files ending with HBM.XML in the fitting. There are other methods to load mapping files, but this way is the simplest. To create a session object The iSession object provides a connection to the background database, and the Itransaction object provides a transaction that can be managed by NHibernate. ISESSIONFACTORY FACTORY = cfg.buildsessionFactory (); ISESSION session = factory.openSession (); ItraSaction Transaction = session.begintransaction (); Then come to Load, Save and Query Your object Now you can use the traditional .NET method to manipulate the object. 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 change to the db and close the iSession Transaction.commit (); session.close (); As you can see, what is important about NHIBERANTE is so simple. Continue and query your database to verify the new record in the User table. The important thing now is that you are going to worry about business objects and tell NHibernate when processed. Let us tell you that when you have a userid, how to get an object (for example, when you log in to your website). Just one sentence, you can open the session, get it in Key. // Open Another session to Retrieve the Just Inserted User Session = factory.opensesis (); User Joecool = (user) session.load (TypeOf (user), "joe_cool"); The User object you get is still in the survival cycle! Change its properties and persisted through Flush () to the database. // set Joe Cool's Last Login Property Joecool.lastlogon = DATETIME.NOW; // Flush the changes from the session to the database Session.flush (); What you have to do is made through NHibernate to make changes you need, and call the session's Flush () method submitted. Verify the database, check the changes in "LastLogon" in the record of the user ID "Joe_cool". There is also better, you can get the objects from the table in the way in system.collections.ilist. as follows IList userList = session.createcriteria (TypeOf (user)). List (); Foreach (User UserList) { System.Diagnostics.debug.writeline (user.id "Last Logged In AT" User.lastlogon); } This query will return all table records. Often need to do more controls, for example, users who have been logged in from March 14, 2004 10:00 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); } There is also a pile of robust inquiry in the document that allows you to call, just let you have a certain understanding of the powerful tools provided by NHibernate. Finally, call the close () method of the session object, release the ADO.NET connection resources used by NHibernate. // Tell NHibernate to Close this session session.close (); more specifically… You have completed the creation of objects, persistent, and returns it through condition query or key value queries. I believe that you have already got happiness. Now you have a roughly understanding of NHibernate. If you can read a lot from Hibernate 2.0.3 documentation, you will get help (NHibernate document is still in the early stage, now just copying the Hibernate). Enjoy! And happy nhibernating! Mike doerfler Once again, all rights from Glen Smith A hitchhiker's guide to hibernate Translated by: jason xie Published: 2005-02-24