Tải bản đầy đủ (.pdf) (276 trang)

NHibernate 2 free ebook download

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.2 MB, 276 trang )

www.it-ebooks.info


NHibernate 2
Beginner's Guide

Rapidly retrieve data from your database into .NET objects

Aaron B. Cure

BIRMINGHAM - MUMBAI

www.it-ebooks.info


NHibernate 2
Beginner's Guide

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.



First published: May 2010

Production Reference: 1050510

Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847198-90-7
www.packtpub.com

Cover Image by Louise Barr ()

www.it-ebooks.info


Credits
Author

Editorial Team Leader

Aaron B. Cure

Aanchal Kumar

Reviewers

Project Team Leader


Jason Dentler

Priya Mukerji

Fabio Maulo
Project Coordinator
Ashwin Shetty

Acquisition Editor
Usha Iyer

Proofreader
Lynda Sliwoski

Development Editor
Chaitanya Apte

Production Coordinator
Shantanu Zagade

Technical Editor
Ajay B. Chamkeri

Cover Work
Shantanu Zagade

Copy Editor
Leonard D'Silva
Indexer
Monica Ajmera Mehta


www.it-ebooks.info


About the Author
Aaron Cure is an avid developer, instructor, and innovator. During his 10 years in the
military as a linguist and a satellite communications repair technician, he learned that his
real love was computer programming.
After various throes with PHP, Classic ASP, VB, and a brief encounter with Java/JSP, he found a
real passion for the .NET framework. After searching for a "better way" to carry out database
storage and retrieval, Aaron stumbled across the NHibernate framework.
Unsatisfied with the options for interacting with this great framework, he founded the
NHibernate Generation project (nhib-gen) on SourceForge to reduce the "barrier to entry"
for most developers.
Aaron and his family run a small consulting and web hosting company doing web design and
custom software development for various organizations across the country. One of their
more interesting projects has been software to control laser cutting machines.
In his spare time, he also enjoys developing projects with his daughters, using everything
from Lego NXT (using C# and Bluetooth communications) to the Microchip PIC platform
(using JAL and USB). He also collects and restores classic farm tractors, engines, and farm
equipment as well as semi trucks and trailers. He and his family display them at tractor
shows, parades, schools, and various other community events.
This book is dedicated to my beautiful and talented wife, Sherry, and my
two wonderful daughters, Kaitlyn and MacKenzie. Without their love and
support, this book would have never been written.
I would also like to thank my parents, Karen and Chuck, as I wouldn't be
here without them.
Special thanks to my editors at Packt Publishing, who had more patience
with me than I think I would have had and stuck with me throughout.


www.it-ebooks.info


About the Reviewers
Jason Dentler started tinkering with computers as a kid in the late 80s. As a college
freshman, he got a job as an intern for a small call center company. Eight years later, he found
himself coding for the entire call center division of a Fortune 500 company at their Global
Technology Center in Las Vegas, Nevada. From there, he moved back to Texas and now works
in higher education. He is an active participant in the NHibernate community and blogs about
NHibernate, .NET, and programming in general at .
I'd like to thank my NHibernate friends Fabio, Tuna, Jose, and Oren for
their support and mentorship, and Scott Guthrie, who with a single tweet,
literally made my blog an overnight success.

Fabio Maulo is the NHibernate development team leader.

www.it-ebooks.info


www.it-ebooks.info


Table of Contents
Preface
Chapter 1: First Look

1
7

What is NHibernate?

Why would I use it?
Where do I get it?
Can I get help using NHibernate?
Database table
The XML mapping file (hbm.xml)
Plain Old CLR Object ( POCO )
Data access
Look how easy it is to use!
Summary

Chapter 2: Database Layout and Design
Before you get started
Laying the foundation—table layouts
Time for action – creating an ordering system database
Table layouts
NHibernate assigned IDs
Relationships
Normal Form
Putting it all together
Time for action – adding some tables to our Ordering system database
Summary

Chapter 3: A Touch of Class

8
8
8
9
9
10

11
11
12
14

15
15
16
16
19
20
21
25
26
26
35

37

Start up our applications
Creating objects
Time for action – creating our first class
Public properties and private variables

www.it-ebooks.info

37
37
38
45



Table of Contents

Time for action – adding a few properties
Converting SQL database types to .NET types
Properties for Foreign Keys
Summary

Chapter 4: Data Cartography

46
50
51
54

55

What is mapping?
Types of mapping
XML mapping
Getting started
Classes
Properties
ID columns
Mapping our types
Time for action – mapping basic types
Relationships
One-to-many relationships
Many-to-many relationships

Getting started
Time for action – mapping relationships
Fluent mapping
Summary

55
56
56
57
57
58
59
60
60
72
72
74
76
77
79
82

Chapter 5: The Session Procession

83

What is an NHibernate session?
Time for action – getting ready
What is a session factory?
Creating your first session

Why do we call .Commit()?
NHibernate session versus database session?
Time for action – creating a session and doing some CRUD
Sessions in ASP.NET
Summary

Chapter 6: I'm a Logger

83
84
93
94
95
96
96
102
104

105

Why do we need to log?
Why log4net?
Getting started
Configuration
Time for action – adding some logging
NHibernate log messages
Appenders

105
106

107
108
110
113
115
[ ii ]

www.it-ebooks.info


Table of Contents

Creating a logger
Time for action – adding some custom logging
Summary

Chapter 7: Configuration

118
120
123

125

Looking back
The basics of configuration
Taking a look at the SQL
Abstracting the configuration
Time for action – moving our configuration
XML configuration

Summary

Chapter 8: Writing Queries

125
126
129
130
132
135
136

137

Using Data Access Objects
The basic Data Access Object
Time for action – creating our basic Data Access Object
Data Access Object methods
Time for action – adding some CRUD methods
Coding some GetX() methods
The FieldNames structure
Time for action – expanding our capabilities
The ICriteria object
Creating a GetAll() method
Paging and Sorting GetAll() methods
Filtering ICriteria
Time for action – replacing our inline code
Summary

Chapter 9: Binding Data


137
138
139
143
146
149
150
152
154
155
157
159
161
162

163

Why should we use data binding?
Time for action – adding an ASP.NET project
Basic data binding techniques
Common data binding methods
A simple templated control
Creating a control instance
The <asp:ListView> control
The <asp:ObjectDataSource> control
Time for action – adding our first data bound control
Direct data binding
One last control—the <asp:FormView>
Summary

[ iii ]

www.it-ebooks.info

164
164
170
173
176
177
179
180
182
188
190
195


Table of Contents

Chapter 10: .NET Security

197

Built-in controls
Time for action – adding a login to our page
Membership providers
Location security
Configuring our provider
Time for action – create a membership provider

User roles
Role providers
Provider configuration
Summary

Chapter 11: It's a Generation Thing

197
200
201
202
204
205
209
210
210
212

213

Judging requirements
CodeSmith
nhib-gen
AjGenesis
Visual NHibernate
MyGeneration
Time for action – using MyGeneration
NGen NHibernate Code Generator
NHModeller
Microsoft T4 templates

T4 hbm2net
Summary

214
215
217
218
221
221
223
227
228
232
232
233

Chapter 12: Odds and Ends

235

Unit of Work and Burrow
How does this relate to NHibernate?
Blog.Net blogging components
maxRequestLength
Converting CSS templates
Time for action – converting a CSS template
XML documentation & GhostDoc
Summary

Appendix: Pop Quiz Answers


235
237
237
237
238
239
246
248

249

Chapter 2 – Database Layout and Design
Relationships
Chapter 3 – A Touch of Class
Mapping
Chapter 4 – Data Cartography
Class mapping
[ iv ]

www.it-ebooks.info

249
249
249
249
250
250



Table of Contents

Chapter 5 – The Session Procession
Creating and updating records
Chapter 6 – I'm Logger
Logging
Chapter 7 – Configuration
Basic configuration
Chapter 8 – Writing Queries
Fieldnames and ICriteria
Chapter 9 – Binding Data
Basic data binding
Chapter 10 – .NET Security
Access configuration
Chapter 12 – Odds and Ends
Burrowing in

250
250
250
250
251
251
251
251
251
251
252
252
252

252

Index

253

[˘]

www.it-ebooks.info


www.it-ebooks.info


Preface
NHibernate is a popular, fast growing Object-Relational Mapper (ORM) with a helpful
community of seasoned developers. It is used in thousands of commercial and open
source projects.
Armed with a set of simple (and mostly free) tools and the knowledge you'll gain from this
book, you can quickly and easily create an entire data-bound website, desktop application,
windows or web service, or virtually any other .NET project you can conceive.

What this book covers
Chapter 1, First Look, discusses what an object-relational mapper is, what NHibernate is, and
the features it provides us.
Chapter 2, Database Layout and Design, discusses how your database is constructed, how
the data is related, and how to optimize it for the best performance using NHibernate.
Chapter 3, A Touch of Class, explains how creating classes to represent your data makes it
easy for you to work with the data and allows you to branch from the design of the database,
if need be.

Chapter 4, Data Cartography, deals with the actual interface to the database with
NHibernate, either using XML mapping files, Fluent NHibernate, or no mapping at all. We
also talk about lazy loading, using a fieldnames structure to help avoid typos, and generating
the database from our mapping files or classes.
Chapter 5, The Session Procession, teaches you how to create NHibernate sessions, which
use database sessions to retrieve and store data into the database.
Chapter 6, I'm a Logger, teaches you how to use the log4net logging framework for
creating our own logs and tap into the information provided by NHibernate (including
SQL statements) to monitor and troubleshoot our application.

www.it-ebooks.info


Preface

Chapter 7, Configuration, explains how to configure our application so, we are ready to
retrieve and store data into our database. Additional configuration options are discussed, as
well as optional configuration properties for particular situations.
Chapter 8, Writing Queries, discusses using NHibernate to actually retrieve data, to include
individual records and collections of records. We talk about filtering records and using the
fieldnames structure we created earlier to speed up our development. We also talk about
adding parameters to make paging and sorting work in data-bound controls.
Chapter 9, Binding Data, explains how to use the data methods we created earlier to build
a web application that uses our data access layer, the ObjectDataSource, and other data
controls to retrieve, display, and even insert/update database data.
Chapter 10, NET Security Providers, presents information about controlling access to and
restricting the usage of data within a .NET web application. We discuss the use of custom
membership and role providers with NHibernate to control access to information.
Chapter 11, It's a Generation Thing, discusses how to use code generation techniques such
as CodeSmith, NHib-Gen, and MyGeneration to automatically generate our data access layer

to get us up and running that much quicker.
Chapter 12, Odds and Ends, discusses some advanced topics such as the Burrow session
management framework and the NHibernate SchemaExport tool.

What you need for this book
To successfully complete the examples in this book, you will need a copy of either Visual
Studio 2008 or 2010. You can use any version as long as it includes the web application
projects. This could be either a Visual Web Developer Express version or any full version
such as Professional.
In addition to Visual Studio, you will also need a SQL database server. The examples
are generated using SQL Server Express 2008 and SQL Server Management Studio
(SSMS) Express.
You will also need to download the NHibernate binary files from sourceforge.net.

Who this book is for
This book is for new and seasoned developers of .NET web or desktop applications who
want a better way to access database data. It is a basic introduction to NHibernate, with
enough information to get a solid foundation in using NHibernate. Some advanced concepts
are presented where appropriate to enhance functionality or in situations where they are
commonly used.
[˘]

www.it-ebooks.info


Preface

Conventions
In this book, you will find several headings appearing frequently.
To give clear instructions on how to complete a procedure or task, we use:


Time for action – heading
1.

Action 1

2.

Action 2

3.

Action 3

Instructions often need some extra explanation so that they make sense, so they are
followed with:

What just happened?
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:

Pop quiz – heading
These are short multiple choice questions intended to help you test your own understanding.

Have a go hero – heading
These set practical challenges and give you ideas for experimenting with what you
have learned.
You will also find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "This will give us a new DLL project called

Ordering.Data inside a folder named Ordering, which contains a solution named
Ordering."

[]

www.it-ebooks.info


Preface

A block of code is set as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace Ordering.Data
{
class OrderHeader
{
}
}

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
public class OrderHeader
{
public OrderHeader() { }
}

Any command-line input or output is written as follows:
07:18:08.295 [10] INFO NHibernate.Cfg.Configuration - Mapping resource:

Ordering.Data.Mapping.Address.hbm.xml

New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: Right-click on the Ordering.
Console application, and select Add | New Item.
Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

[]

www.it-ebooks.info


Preface

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to , and
mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the
SUGGEST A TITLE form on www.packtpub.com or e-mail
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.

Downloading the example code for the book
Visit />downloads/8907_Code.zip to directly download the example code.
The downloadable files contain instructions on how to use them.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you would report this to us. By doing so, you can save other
readers from frustration and help us improve subsequent versions of this book. If you
find any errata, please report them by visiting />selecting your book, clicking on the let us know link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata
will be uploaded on our website, or added to any list of existing errata, under the Errata
section of that title. Any existing errata can be viewed by selecting your title from
/>
[]

www.it-ebooks.info


Preface

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protection of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.


Questions
You can contact us at if you are having a problem with any
aspect of the book, and we will do our best to address it.

[]

www.it-ebooks.info


1

First Look
It seems like every single project we begin as developers, no matter how simple,
requires some sort of storage. Sometimes this is a simple collection of values in
an XML file or a key-value pair in a properties file.
However, more often, we need to have access to larger volumes of data,
represented in multiple related database tables. In either case, we are generally
forced to reinvent the wheel, to create new data retrieval and storage methods
for each piece of data we want to access. Enter NHibernate.

In this chapter, we will discuss:


What NHibernate is and why we should use it



HBM mapping files




Plain Old CLR Objects (POCOs)



Data access classes



A simple web page databound to a collection of NHibernate objects

www.it-ebooks.info


First Look

What is NHibernate?
That's a great question, and I'm glad you asked! NHibernate is an open source persistence
layer based on Object-Relational Mapping Techniques or simply a tool that creates a "virtual
representation" of database objects within the code. According to the creators of NHibernate:
NHibernate is a port of Hibernate Core for Java to the .NET Framework. It handles
persisting plain .NET objects to and from an underlying relational database. Given
an XML description of your entities and relationships, NHibernate automatically
generates SQL for loading and storing the objects.
In simple terms, NHibernate does all the database work, and we reap all the benefits! Instead
of writing reams of SQL statements or creating stored procedures that "live" in a different place
than our code, we can have all of our data access logic contained within our application.
With a few simple "tricks" that we'll discuss in Chapter 4, Data Cartography, not only will our
queries be effective, but they will also be validated by the compiler. Therefore, if our underlying
table structure changes, the compiler will alert us that we need to change our queries!


Why would I use it?
Unless you love to write CRUD (Create, Retrieve, Update, Delete) methods over and over
for each of the pieces of data you need to access (and I don't know a single developer who
does), you are probably looking for a better method. If you're like me, then you know how
to lay down an elegant database design (and if you don't, take a peek at Chapter 2, Database
Layout and Design). Once the database is ready, you just want to use it!
Wouldn't it be nice to create a few tables, and in just a few minutes, have a working set of
forms that you can use for all of your basic CRUD operations, as well as a full set of queries
to access the most common types of data? We'll discuss some of the ways to automatically
generate your NHibernate data files in Chapter 11, It's a Generation Thing.

Where do I get it?
The home of the NHibernate project is at , while the code is
housed at SourceForge ( />If you download the latest GA (Generally Available, also known as final or stable) bin release
(binaries only, no source code) of the NHibernate project, you will have everything you need
to get started. As of this writing, the current release is NHibernate-2.1.2.GA-bin, and all
of the examples have been developed using this version. This version is available at
/>2.1.2GA/NHibernate-2.1.2.GA-bin.zip.
[]

www.it-ebooks.info


Chapter 1

Can I get help using NHibernate?
There is a great community site for NHibernate on the Web called the NHibernate Forge. It is
located at and it provides a wealth of resources for the new
and veteran NHibernate user.


Have a go hero – looking at some sample files
A basic NHibernate project is composed of three major parts. You will need a mapping file
to tell NHibernate how the database is or should be (see the Mapping our types section in
Chapter 4) constructed, some data access methods to tell NHibernate what data you want to
retrieve or store into the database, and a POCO to allow you to interact with the data. While
XML mapping files are commonly used in NHibernate projects, they are not the only way to
map data to POCOs (more in Chapter 4).
Take a look at some sample files, but don't get too hung up on them. We'll go into more
detail in the later chapters.

Database table
The first item we need to use NHibernate is a database table to map against. In the following
screenshot, we define a table named Login with a Primary Key column named Id, two
nullable fields to store the FirstName and LastName, and two non-nullable fields to
store the UserName and Password.

[]

www.it-ebooks.info


First Look

The XML mapping file (hbm.xml)
The following code snippet shows the Login.hbm.xml mapping file for this simple table,
with all the information required not only to map the data, but also to create the database
from the metadata contained within the mapping file. If we do not want to be able to
generate the database from the mapping file, then we can omit all of the sql-type,
unique, and index properties.

Some immediate information you might pick up from the file are the name of the class
that NHibernate will use to map database rows (BasicWebApplication.Common.
DataObjects.Login), which is defined in the <class> tag. This says that the
BasicWebApplication.Common.DataObjects.Login object is contained in the
BasicWebApplication assembly. It further defines that the Login table is the database
table we will be mapping to, using the <table> element.
There is an <id> tag that defines what the unique identifier (ID) is for the database record,
as well as how that identifier is expected to be created. In our case, the class="hilo"> tag specifies that we will be using the hi/lo Persistent Object ID (POID)
generator for IDs.
The four string fields FirstName, LastName, UserName, and Password are then mapped
to the four database columns of the same names, using the tag.
<?xml version="1.0" encoding="utf-8" ?>
namespace="BasicWebApplication.Common.DataObjects"
assembly="BasicWebApplication">
<class name="Login" table="Login">
<id name="Id" type="Int32" unsaved-value="null">
<column name="Id" />
<generator class="hilo" />
</id>




</class>
</hibernate-mapping>

[ 10 ]


www.it-ebooks.info


Chapter 1

Plain Old CLR Object ( POCO )
The Login.cs class shown in the following code snippet is the POCO, the class that
NHibernate will use to map database rows. Each row in the database returned will be
instantiated (also known as "newed up") in a new instance of the Login class. The collection
of rows will be returned as a generic IList of Login objects or an IList<Login>.
Notice how each property in the class Login maps directly to a property element in
the hbm.xml file. We really have five public properties on this object, Id, FirstName,
LastName, UserName, and Password. Each of these properties was defined earlier in the
hbm.xml file and mapped to a database field.
When NHibernate retrieves records from the database, it will create a new instance
(also known as "new up") of a Login object for each record it retrieves and use the
public "setter" (set function) for each property to fill out the object.
public partial class Login
{
public Login() { }
public
public
public
public
public

virtual
virtual
virtual
virtual

virtual

int Id
string
string
string
string

{ get; set; }
FirstName { get; set; }
LastName { get; set; }
UserName { get; set; }
Password { get; set; }

}

Data access
The final class, LoginDataControl.cs, provides CRUD methods for data retrieval, storage,
and removal. The session variable is an NHibernate session (you can find out more about
session management in Chapter 5, The Session Procession).
This class defines a few simple CRUD methods that are used quite often when manipulating
database records. The GetById(int id) function allows the user to pass in an integer and
retrieve the record with that ID. The GetAll() method returns all of the records in a given
table. GetCountOfAll() returns a count of the records in the table, while allowing controls
that handle pagination and record navigation to function.
public class LoginDataControl
{
public LoginDataControl() { }
ISession session;


[ 11 ]

www.it-ebooks.info


First Look
public Login GetById(int id)
{
Login retVal = session.Get<Login>(id);
return retVal;
}
public IList<Login> GetAll()
{
ICriteria criteria = session.CreateCriteria<Login>();
IList<Login> retVal = criteria.List<Login>();
return retVal;
}
public int GetCountOfAll()
{
return GetAll().Count;
}
}

Look how easy it is to use!
The sample Login.aspx ASP.NET file shows one of the best reasons why we use
NHibernate. By using an ObjectDataSource, we can map the NHibernate objects directly to
the data-bound controls that will display or interact with them. All we have to do is create an
ObjectDataSource to retrieve the data from our data access class (LoginDataControl.cs),
create a set of form fields to display the data (like the <asp:GridView> "LoginGrid" below),
and let ASP.NET handle all of the tedious work for us. By the way, this page will work exactly

as shown—there is no page logic in the code behind or anywhere else.
All we have in this code is a GridView to present the information and an ObjectDataSource
to interact with our DataAccess classes and provide data for the GridView. The GridView
has BoundField definitions for all of the fields in our database table as well as Sorting and
Paging functions. The ObjectDataSource has methods mapped for Select, Select Count,
Insert, and Update. When the GridView needs to perform one of these functions, it
relies on the ObjectDataSource to handle these operations. Working in tandem, these two
controls (as well as nearly any other data bound control) can provide a very quick and simple
interface for your data!
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="BasicWebApplication.Web._Default" %>
" />[ 12 ]

www.it-ebooks.info


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×