Reprint: nhib.pdf Quick Start

Source: Internet
Author: User
Tags log4net


What is nhib.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: Write SQL statements for table Creation
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 nhib.pdf
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 specified User object.
Step 2: generate a. Net 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 nhib.pdf. 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"?>
<Hibernate-mapping xmlns = "urn: nhibernate-mapping-2.0">
<Class name = "nhib.pdf. Examples. QuickStart. User, nhib.pdf. 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>
</Hibernate-mapping>
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 load the class NHibernate. Examples. Examples. QuickStart. User from the accessories. Nhib.pdf follows the same rules as. Net Framework to load types. If you are confused about how to specify a type, see. Net Framework SDK.
Let's skip the id tag to discuss the property tag. Let's take a brief look at the work that nhib.pdf has to do. The value of the name attribute is exactly the property of our. Net class. The column attribute value will be the field in our database. The type attribute is optional (if you do not specify it, nhib will use reflection for optimal speculation ).
Well, let's go back to the tag id. You can guess that this tag will be the primary key mapped to the database table. Indeed, the composition of the id tag is similar to the property tag we just looked. The fields mapped to the target database.
The embedded generator label tells NHibernate how to generate a primary key (it will generate a primary key for you, no matter what type you specify, but you must tell it ). In our example, we set it to assigned, which means that our object will generate its own primary key (after all, the User object often needs a UserID ). If you want to generate a primary key for NHiberante, you are interested in setting uuid. hex and uuid. 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 = "nhibction" type =" System. Configuration. NameValueSectionHandler, System, Version = 1.0.3300.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 "/>
</ConfigSections>
<Nhib.pdf>
<Add
Key = "hibernate. connection. provider"

Value = "nhib.pdf. Connection. DriverConnectionProvider"
/>
<Add
Key = "hibernate. dialect"
Value = "nhibect. Dialect. MsSql2000Dialect"
/>
<Add
Key = "hibernate. connection. driver_class"
Value = "nhib.pdf. Driver. SqlClientDriver"
/>
<Add
Key = "hibernate. connection. connection_string"
Value = "Server = localhost; initial catalog = nhibalog; Integrated Security = SSPI"
/>
</Nhib.pdf>
</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 show the magic of nhib.pdf
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:
Create a Configuration object
Let Configuration know what type of objects you will store
Create a Session object for the database you selected
Load, Save, and Query your objects
Submit the object to the database through the Flush () method of the Session.
To make it clearer, let's look at some code.
First, create a Configuration object
The Configuration object can parse mappings between all. Net objects and the background database.
Configuration cfg = new Configuration ();
Cfg. AddAssembly ("nhibles. 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, create a Session object.
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 nhibtasks that this object shocould be saved
Session. Save (newUser );
// Commit all of the changes to the DB and close the ISession
Transaction. Commit ();
Sess

Ion. 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, call the Close () method of the Session object to release the ADO. Net connection resource used by nhib.pdf.
// Tell nhibto 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.

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.