NHibernate Reading Notes-Hello NHibernateⅠ
时间:2010-09-18 来源:Akon.S
Hello NHibernate
2.1 “Hello World” with NHibernate
NHibernate applications define persistent classes that are mapped to database tables. Our “Hello World” example consists of one class and one mapping file. Let’s see what a simple persistent class looks like, how the mapping is specified, and some of the things you can do with instances of the persistent class using NHibernate.
2.1.1 Installing NHibernate
Before you can start coding the “Hello World” application, you must first install NHibernate. You then need to create a new Visual Studio solution to contain the sample application.
NHibernate 1.2.1GA can be downloaded via http://www.nhforge.org. Click the “download” tab and locate “NHibernate Core.” From there you can find and download the NHibernate 1.2.1.GA.msi file.
Although the book is written for NHibernate 1.2.1GA, we’re aware that many people are using NHibernate 2.0 Beta. We’ve therefore ensured our first tutorial applies to both of these versions of NHibernate.
Once you’ve downloaded and installed NHibernate, you’re ready to create a new solution and start using it.
2.1.2 Create a new Visual Studio project
For the example application, you should create a new blank project with Visual Studio. This is a simple application, so the easiest thing to create is a C# Console Application. Name your project HelloNHibernate. Note that you can also use NHibernate with VB.NET projects, but in this book, we’ve chosen to use C# examples.
The application will need to use the NHibernate library, so the next step is to reference it in your new project. To do this, follow these steps:
1 Right-click the project and select Add Reference.
2 Click the Browse tab and navigate to the folder where NHibernate is installed. By default, NHibernate resides in the C:\Program Files\NHibernate\bin\net2.0\ folder.
3 From the list of assemblies, select NHibernate.dll. Click OK to add this reference to your solution. By default, the Console Application should have added a file called Program. cs to your solution. Locate this file and open it. Note that, in console applications, this will be the first thing that is run when you execute the program.
4 Reference the NHibernate library at the top of the Program.cs file with the using NHibernate, using System.Reflection and NHibernate.Cfg statements, as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate; using NHibernate.Cfg; using System.Reflection; namespace NHibernateInAction { class Program { static ISessionFactory factory; static void Main(string[] args) { } } }
Now that your solution is set up, you’re ready to start writing your first NHibernate
application.
2.1.3 Creating the Employee class
The objective of the sample application is to store an Employee record in a database and to later retrieve it for display. The application needs a simple persistent class, Employee, which represents a person who is employed by a company.
In Visual Studio, add a new class file to your application and name it Employee.cs when prompted. Then enter the code from listing 2.1 for the Employee entity.
namespace NHibernateInAction { class Employee { public int id; public string name; public Employee manager; public string SayHello() { return string.Format("'Hello World!', said {0}.", name); } } }
The Employee class has three fields: the identifier, the name of the employee, and a reference to the employee’s manager. The identifier field allows the application to access the database identity—the primary key value—of a persistent object. If two instances of Employee have the same identifier value, they represent the same row in the database. We’ve chosen int for the type of the identifier field, but this isn’t a requirement. NHibernate allows virtually anything for the identifier type, as you’ll see later.
Note that you use public fields here rather than properties. This is purely to make the sample code shorter; it isn’t always considered good practice.
Instances of the Employee class may be managed (made persistent) by NHibernate, but they don’t have to be. Because the Employee object doesn’t implement any NHibernate-specific classes or interfaces, you can use it like any other .NET class:
Employee fred = new Employee();
fred.name = "Fred Bloggs";
Console.WriteLine( fred.SayHello() );
It may look like we’re trying to be cute; in fact, we’re demonstrating an important feature that distinguishes NHibernate from some other persistence solutions. The persistent class can be used with or without NHibernate—no special requirements are needed.Of course,you came here to see NHibernate, so let’s first set up the database and then demonstrate using NHibernate to save a new Employee to it.
2.1.4 Setting up the database
Your first step is to open Microsoft SQL Server Management Studio, connect to your database server, and open a new query window. Type the following in the SQL window to quickly create a new database:
CREATE DATABASE HelloNHibernate
GO
Run this SQL to create the database. The next step is to switch to that database and create a table to hold your Employee data. To do so, delete the previous SQL and replace it with the following
USE HelloNHibernate
GO
CREATE TABLE Employee (
id int identity primary key,
name varchar(50),
manager int )
GO
Run this code: you’ve created a place to store your Employee entities. You’re now ready to see NHibernate in action!
Note that, in chapter 9, we show you how to use NHibernate to automatically create the tables your application needs using just the information in the mapping files. There’s some more SQL you won’t need to write by hand!
2.1.5 Creating an Employee and saving to the database
The code required to create an Employee and save it to the database is shown in listing 2.2. It comprises two functions: CreateEmployeeAndSaveToDatabase and Open- Session. You can type these functions into your Program.cs file below the static void Main() function in the Program class.
static void CreateEmployeeAndSaveToDatabase() { Employee tobin = new Employee(); tobin.name = "Tobin Harris"; using (ISession session = OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Save(tobin); transaction.Commit(); } Console.WriteLine("Saved Tobin to the database"); } } static ISession OpenSession() { if (factory == null) { Configuration c = new Configuration(); c.AddAssembly(Assembly.GetCallingAssembly()); factory = c.BuildSessionFactory(); } return factory.OpenSession(); } static ISessionFactory factory;
2.1.6 Loading an Employee from the database
Let’s start by adding code that can retrieve all Employees from the database in alphabetical order.
static void LoadEmployeesFromDatabase() { using (ISession session = OpenSession()) { IQuery query = session.CreateQuery( "from Employee as emp order by emp.name asc"); IList<Employee> foundEmployees = query.List<Employee>(); Console.WriteLine("\n{0} employees found:", foundEmployees.Count); foreach (Employee employee in foundEmployees) Console.WriteLine(employee.SayHello()); } }
The literal string "from Employee as emp order by emp.name asc" is an NHibernate query, expressed in NHibernate’s own object-oriented Hibernate Query Language (HQL). This query is internally translated into the following SQL when query.List() is called:
select e.id, e.name, e.manager
from Employee e
order by e.name asc
All SQL is generated at runtime (at startup, where possible).