Nhib.pdf is an object persistence Class Library Based on. NET for relational databases. It is a famous hibernate. Net version.
Nhib.pdf is used to put your.. Net objects are persistently stored in the underlying relational database. you do not need to write SQL statements to operate on these objects. NH will replace you. in your code, you only need to care about these objects. NH generates SQL statements and can get the correct information for you.
Development Process
Hnibernate will have some tools to help you, such as generating a schema, generating classes based on the mapping file, and updating the schema (recommended by a new developer ). however, in this document, the premise is that you have manually created a database. net class writing...
Here is what we want to do:
1. Create a table in the database that persists the. NET class.
2. Create the. NET class to be persisted.
3. Create a ing file to show NH how to persist the attributes of these classes.
4. Create the configuration file of NH to tell NH how to connect to the database.
5. Use APIs provided by NH.
Step 1: Create a database table
What we are doing is a very simple NH example. In this example, we implement a basic user management subsystem. We will use a user table (SQL Server 2000 ):
Use nhib.pdf
Go
Create Table users (
Logonid varchar (20) not null default '0 ',
Name varchar (40) default null,
Password varchar (20) default null,
Emailaddress varchar (40) default null,
Lastlogon datetime default null,
Primary Key (logonid)
)
Go
I use ms SQL Server 2000, but if you find a. NET data provider driver for any database, you can use any database.
Step 2: Create a. Net class:
When we have such a bunch of users, we need some object to save. NH works through the attributes of the reflection object, so we add attributes to the objects needing persistence. A class corresponding to the above database structure can be written as follows:
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 code above, writing the attribute and constructor as public-NH does not require this. You can use public, protected, internal, or private to mark your attributes.
Step 3: Write A Mapping File)
Now we have database tables and. net class, we also need to tell NH how to map between the database and class. this requires a ing file. the simplest (and the best maintainability) method is to write a ing file for each class. If you name it "XXX. HBM. XML "ing files and XXX class files are placed in the same directory. NH makes everything easy. here, our user. HBM. XML may look like this:
<? XML version = "1.0" encoding = "UTF-8"?>
<Hibernate-mapping xmlns = "urn: nhibernate-mapping-2.0">
<Class name = "Nhibernate. Demo. Quickstart. User, Nhibernate. Demo. Quickstart" table = "users">
<ID name = "ID" column = "logonid" type = "string (20)">
<Generator class = "assigned"/>
</ID>
<Property name = "username" column = "name" type = "string (40)"/>
<Property name = "password" type = "string (20)"/>
<Property name = "emailaddress" type = "string (40)"/>
<Property name = "lastlogon" type = "datetime"/>
</Class>
</Hibernate-mapping>
Let's take a look at this interesting ing file: The first tag is class. Here we map the type name (Class Name and Assembly name) to the user table in the database (here it is somewhat different from hibernate, we must tell the NH where the class comes from. this difference is caused. net and Java reflect mechanisms caused by different-zyyang ). in this case, we start from assembly nhib.pdf. demo. load nhib.pdf in Quickstart. demo. quickstart. user class .. NH compliance. net Framework uses reflection to load type rules-so if you have any questions, check them.. NET Framework SDK.
Let's skip the "ID" tag for the moment. Let's talk about the property node first. the property value of "name" is written by us.. Net class. The column attribute value is the field name corresponding to the 'net class attribute in the database. the Type attribute is optional (if you do not specify it, NH will give the most suitable one), but we recommend that you include this attribute. hibernate users will notice that the length value is given in the type attribute value, because ADO. net.
Let's return the "ID" tag. You may guess this tag is related to the primary key mapped to the table. correct. the format of the ID tag is similar to that of the property tag. we map the property (name) to the field (colume) of the target database ).
These embedded generator tags tell NH how to generate the primary key (NH can easily generate one for you, no matter what type, as long as you tell it how to do it ). in our example, we set it to "assigned", which means "Our object will generate its own key" (the user object will always need a userid ), if you are happy to make NH generate instead of you, you will. hex and UUID. string class (see the CHM documentation ).
Tip: If you use vs.net for compilation, set build action. HBM. the XML file is bound to Asssembly as a resource, so that the ing file becomes part of Asssembly. we will understand the importance of this step later.
Step 4: Create a database configuration file
So far, we have not told NH where to find the database. The most direct method is to give NH a part in your program's configuration file, which is like this:
<? 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 = "nhib.pdf. 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; user id = someuser; Password = somepwd; min pool size = 2"/>
</Nhib.pdf>
</Configuration>
In the preceding example, the sqlclient driver is used to connect to the local Nhibernate database and use the provided user and password. Other configuration items are available. For more information, see the documentation.
Step 5: Start to experience the magic of nhib.pdf
All the hard work has been done. If all the work is completed, you will have the following results:
Your User. CS-the. NET class to be persisted.
Æ user. HBM. XML- ing File
App. config-configuration file with ado.net connection information (you can also specify it in the Code)
Contains a database table called a user.
Using nhib.pdf in the code is very simple:
1. Create a configuration object.
2. Tell configuration which object you want to persist.
3. Create a session to connect to the database you set.
4. Load, save, and query your objects.
5. Flush () Your session
Well, let's look at some code:
Create a configuration object ....
The configuration object knows the ing relationships between all. Net classes and backend databases,
Configuration CFG = new configuration ();
Cfg. addassembly ("nhib.pdf. Demo. Quickstart ");
The configuration object will find all the files ending with. HBM. XML in this Assembly. There are other ways to add the ing file. This may be the simplest one.
Create a session object .......
The isession object represents a connection to the backend database, and the itransaction represents a transaction managed by nhib.pdf ).
Isessionfactory factory = cfg. buildsessionfactory ();
Isession session = factory. opensession ();
Itransaction transaction = session. begintransaction ();
Load, save, and query your objects ......
Now you can use. Net to treat these objects. Do you want to save a new user in the database? You only need:
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 ();
Session. Close ();
This is the benefit of NH. You only need to care about your business objects (BO) most of the time ).
If you need to query an object based on the known user ID, if the session is open, you only need one line:
// Open another session to retrieve the just inserted user
Session = factory. opensession ();
User joecool = (User) Session. Load (typeof (user), "joe_cool ");
In this way, you will get this object and set the attributes of the object. It will be persisted to the database when the next flush () method appears.
// Set joe cool's last login Property
Joecool. lastlogon = datetime. now;
// Flush the changes from the session to the database
Session. Flush ();
Let NH write your modifications to the object. You only need to flush session.
Better yet, you can query a system. Collections. ilist from the database:
Ilist userlist = session. createcriteria (typeof (User). List ();
Foreach (User user in userlist)
{
Console. writeline (user. ID + "Last logged in at" + User. lastlogon );
}
This query will return the content of the entire table, especially when you want more control-like all users who have logged in after pm on March 14,200, you can:
Ilist recentusers = session. createcriteria (typeof (User )). add (expression. GT ("lastlogon", new datetime (2004, 03, 14, 20, 0, 0 ))). list ();
Foreach (User user in recentusers)
{
Console. writeline (user. ID + "Last logged in at" + User. lastlogon );
}
There are many query options in this document, but these are enough to show you the power of hinting.
Don't forget to close your session.
// Tell nhibto to close this session
Session. Close ();