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.Examples
Loading classNHibernate.Examples.QuickStart.User
。
NHibernate
Follow and
.Net Framework
Load types using the same rules. Therefore, if you are confused about how to specify the type, see
.Net Framework SDK
。
Let's skip
id
Label to discuss
property
Label. After a brief look, you will find
NHibernate
The work to be done.
name
The attribute value is exactly ours.
.Net
Class attributes,
column
Attribute values are fields in our database.
type
The property is optional (if you do not specify it,
NHibernate
We will use reflection for the best estimation ).
Okay, let's go back to the tag
id,
You can guess that this label will be the primary key mapped to the database table,
id
Tag composition and what we just saw
property
Labels are similar. The fields mapped to the target database.
Embedded
generator
Tag notification
NHibernate
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 set
assigned,
This means that our object will generate its own primary key (after all
User
An object often needs
UserID
). If you want
NHiberante
Generate a primary key for you. 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="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:
- 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, 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