Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
This book contains quick-paced self-explanatory recipes organized in progressive skill levels and functional areas. Each recipe contains step-by-step instructions about everything necessary to execute a particular task. The book is designed so that you can read it from start to end or just open up any chapter and start following the recipes. In short this book is meant to be the ultimate "how-to" reference for NHibernate 3.0, covering every major feature of NHibernate for all experience levels.This book is written for NHibernate users at all levels of experience. Examples are written in C# and XML. Some basic knowledge of SQL is assumed.
NHibernate 3.0 Cookbook
Credits
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Models and Mappings
Introduction
Mapping a class with XML
Getting ready
How to do it...
How it works...
There's more...
What happens to these mappings?
Surrogate keys and natural IDs
ID generator selection
See also
Creating class hierarchy mappings
Getting ready
How to do it...
How it works...
There's more...
Table per class
Table per concrete class
See also
Mapping a one-to-many relationship
Getting ready
How to do it...
How it works...
There's more...
Lazy loading collections
Lazy loading proxies
Collections
Bags
Lists
Sets
Map
See also
Setting up a base entity class
Getting ready
How to do it...
How it works...
There's more...
See also
Handling versioning and concurrency
Getting ready
How to do it...
How it works...
There's more...
Other methods of optimistic concurrency
See also
Creating mappings fluently
Getting ready
How to do it...
How it works...
See also
Mapping with ConfORM
Getting ready
How to do it...
How it works...
See also
Bidirectional one-to-many class relationships
How to do it...
How it works...
There's more...
Mappings enumerations
How to do it...
How it works...
Creating class components
How to do it...
How it works...
2. Configuration and Schema
Introduction
Configuring NHibernate with App.config
Getting ready
How to do it...
How it works...
There's more...
NHibernate properties
Dialects and drivers
See also
Configuring NHibernate with hibernate.cfg.xml
Getting ready
How to do it…
How it works…
There's more…
See also
Configuring NHibernate with code
Getting ready
How to do it…
How it works…
There's more...
See also
Configuring NHibernate with Fluent NHibernate
Getting ready
How to do it…
How it works…
See also
Configuring NHibernate using ConfORM Mappings
Getting ready
How to do it...
How it works...
There's more...
See also
Configuring NHibernate logging
Getting ready
How to do it...
How it works...
There's more...
Using log4net to troubleshoot NHibernate
See also
Reducing application startup time
Getting ready
How to do it...
How it works...
There's more...
Generating the database
Getting ready
How to do it...
How it works...
There's more...
See also
Scripting the database
Getting ready
How to do it...
How it works...
See also
Using NHibernate Schema Tool
Getting ready
How to do it...
How it works...
There's more...
See also
3. Sessions and Transactions
Introduction
Setting up session per web request
Getting ready
How to do it...
How it works...
There's more...
See also
Setting up session per presenter
Getting ready
How to do it...
How it works...
There's More...
See also
Creating a session ASP.NET MVC action filter
Getting ready
How to do it...
How it works...
There's more...
View models
See also
Creating a Transaction ASP.NET MVC action filter
Getting ready
How to do it...
How it works...
There's more...
Using the Conversation per Business Transaction pattern
Getting ready
How to do it...
How it works...
There's more...
See also
Using session.Merge
Getting ready
How to do it...
How it works...
See also
Using session.Refresh
Getting ready
How to do it...
How it works...
There's more...
See also
Using stateless sessions
Getting ready
How to do it...
How it works...
There's more...
Using dictionaries as entities
Getting ready
How to do it...
How it works...
There's more...
Partially dynamic
Using NHibernate with TransactionScope
Getting ready
How to do it...
How it works...
See also
4. Queries
Introduction
Using Criteria Queries
How to do it...
How it works...
There's more...
See also
Using QueryOver
How to do it...
How it works...
There's more...
See also
Using QueryOver projections and aggregates
How to do it...
How it works...
See also
Using MultiCriteria
How to do it...
How it works...
See also
Using the Hibernate Query Language
How to do it...
How it works...
There's more...
See also
Using MultiQuery
How to do it...
How it works...
See also
Using Named Queries
How to do it...
How it works...
There's more...
Named SQL queries
HQL AddIn
See also
Using Futures
How to do it...
How it works...
There's more...
See also
Eager loading child collections
How to do it...
How it works...
There's more...
See also
Using LINQ to NHibernate
How to do it...
How it works...
See also
Using Detached Queries
Getting ready
How to do it...
How it works...
There's more...
See also
Using HQL for bulk data changes
Getting ready
How to do it...
How it works...
There's more...
Bulk inserts
See also
5. Testing
Introduction
Using NHibernate Profiler
Getting ready
How to do it...
How it works...
There's more...
See also
Fast testing with SQLite in-memory database
Getting ready
How to do it...
How it works...
There's more...
See also
Preloading data with SQLite
Getting ready
How to do it...
How it works...
There's more...
See also
Using the Fluent NHibernate Persistence Tester
Getting ready
How to do it...
How it works...
See also
Using the Ghostbusters test
Getting ready
How to do it...
How it works...
See also
6. Data Access Layer
Introduction
Transaction Auto-wrapping for the data access layer
Getting ready
How to do it...
How it works...
There's more...
See also
Setting up an NHibernate Repository
Getting ready
How to do it...
How it works...
There's more...
See also
Using Named Queries in the data access layer
Getting ready
How to do it...
How it works...
There's more...
See also
Using ICriteria in the data access layer
Getting ready
How to do it...
How it works...
There's more...
See also
Using Paged Queries in the data access layer
Getting ready
How to do it...
How it works...
See also
Using LINQ Specifications in the data access layer
Getting ready
How to do it...
How it works...
There's more...
Specification composition
See also
7. Extending NHibernate
Introduction
Creating an encrypted string type
How to do it...
How it works...
There's more...
See also
Using well-known instance type
How to do it...
How it works...
See also
Using dependency injection with entities
Getting ready
How to do it...
How it works...
There's more...
Bland passwords need salt
See also
Creating an audit-event listener
How to do it...
How it works...
There's more...
See also
Creating and changing stamping entities
How to do it...
How it works...
See also
Generating trigger-based auditing
Getting ready
How to do it...
How it works...
See also
Setting MS Sql's Context Info
Getting ready
How to do it...
How it works...
See also
Using dynamic connection strings
How to do it...
How it works...
See also
8. NHibernate Contribution Projects
Introduction
Configuring the cache
Getting ready
How to do it...
How it works...
There's more...
Entity cache
Query cache
Update timestamp cache
The rules
See also
Configuring the cache with code
Getting ready
How to do it...
How it works...
See also
Property validation with attributes
Getting ready
How to do it...
How it works...
There's more...
See also
Creating validator classes
Getting ready
How to do it...
How it works...
There's more...
See also
Using the Burrows framework
Getting ready
How to do it...
How it works...
There's more...
See also
Setting up full-text search
Getting ready
How to do it...
How it works...
There's more...
Sharding databases for performance
Getting ready
How to do it...
How it works...
Using NHibernate Spatial
Getting ready
How to do it...
How it works...
There's more...
Geography or geometry?
What's this SRID?
Spatial data types
A. Menu
ASP.NET MVC web applications
ASP.NET Web Forms applications
WPF and WinForms applications
Index
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, Packt Publishing, nor its dealers or 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 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: October 2010
Production Reference: 1240910
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-84951-304-3
www.packtpub.com
Cover Image by Javier Barria ( <jbarriac@yahoo.com> )
Author
Jason Dentler
Reviewers
Fabio Maulo
Jose F. Romaniello
Gabriel Nicolas Schenker
Tuna Toksoz
Acquisition Editor
Chaitanya Apte
Development Editor
Rakesh Shejwal
Technical Editor
Paramanand N. Bhat
Indexer
Tejal Daruwale
Editorial Team Leader
Aanchal Kumar
Project Team Leader
Priya Mukherji
Project Coordinator
Prasad Rai
Proofreader
Clyde Jenkins
Graphics
Nilesh Mohite
Production Coordinator
Kruthika Bangera
Cover Work
Kruthika Bangera
Jason Dentler grew up in the small Texas town of Mission Valley. He started tinkering with computers as a kid in the late 1980s, and all these years later, he hasn't stopped. He has worked in different industries. Currently, he builds really awesome software for higher education. He's an Eagle Scout and a graduate of the University of Houston – Victoria.
I'd like to thank my family and friends for all their support, and especially my parents, who encouraged and tolerated my computer obsession all those years. Thanks, Mom & Dad. I love you.
Fabio Maulo has lived his youth in Montecosaro, a small village in the hills of the Marche in Italy. His first computer was a Mac128 in 1984; since then, he has always followed technology of the moment, trying to learn as much as possible. Since the end of past century, he has followed the evolution of ORM, at first in Delphi's world and then the .NET's world. He joined to NHibernate's team in 2007, and since 2008, is leading the project.
Thanks to my father to let me choose between a motorcycle and a computer (and I did buy a computer with the cost of a motorbike). Thanks to my wife who bears my work.
José Fernando Romaniello is a senior developer with ten years of experience in Microsoft technologies. He currently lives in Argentina, and works for GenWise B.V. José has a strong involvement in various open source projects in .Net world, and he actively contributes to uNhAddins, LinqSpecs, and HqlAddin. He enjoys sharing his knowledge in his blog as well as on mailing lists.
I want to thank Fabio Maulo for sharing long talks with me, for teaching me a lot of things about programming, ORMs, and NHibernate.
I want to thank Jason Dentler for choosing me as a reviewer for this great book.
And finally, I want to thank to my beloved wife and my daughter, I couldn't be here without their help.
Gabriel N. Schenker has been working for over 12 years as an independent consultant, trainer, and mentor, mainly on the .NET platform. He is currently working as lead software architect in a mid-size US company based in Austin, TX providing software and services to the pharmaceutical industry, as well as to many well-known universities throughout the US and in many other countries around the world. Gabriel is passionate about software development, and tries to make life of the developers easier by providing guidelines and frameworks to reduce friction in the software development process.
He has used NHibernate in many different commercial projects—web-based as well as windows-based solutions. Gabriel has written many articles and blog posts about different aspects of NHibernate. He is the author behind the well-known NHibernate FAQ blog.
Gabriel is married, and the father of four children. During his spare, time he likes hiking in the mountains, cooking, and reading.
Tuna Toksoz is currently a graduate student at the Department of Aeronautics and Astronautics at MIT. He mainly concentrates on Software Development and Autonomous Systems. He likes to be involved in OSS projects. He contributes to Nhibernate and Castle projects as a committer, and actively participates in many tech-related mailing groups.
This book explains each feature of NHibernate 3.0 in detail through example recipes that you can quickly apply to your applications. These recipes will take you from the absolute basics of NHibernate through its most advanced features and beyond, showing you how to take full advantage of each concept to quickly create amazing database applications.
Chapter 1, Models and Mappings, introduces mappings in XML, Fluent NHibernate, and ConfORM, and includes more advanced topics such as versioning and concurrency.
Chapter 2, Configuration and Schema, explains various methods for configuring NHibernate and generating your database.
Chapter 3, Sessions and Transactions, covers several techniques for proper session and transaction management in your application, including distributed transactions.
Chapter 4, Queries, demonstrates a number of rich query APIs, including the new NHibernate 3.0 LINQ provider and QueryOver API.
Chapter 5, Testing, introduces some techniques you can apply to quickly test your NHibernate applications and includes an introduction to NHibernate Profiler.
Chapter 6, Data Access Layer, shows how to build a flexible, extensible data access layer based on NHibernate and its many query APIs.
Chapter 7, Extending NHibernate, shows a number of ways to customize and extend NHibernate to provide additional services such as audit logging and data encryption.
Chapter 8, NHibernate Contribution Projects, introduces several NHibernate Contribution projects, adding features such as caching, data validation, full text search, geospatial data, and horizontal partitioning of databases.
Appendix, Menu, is designed to guide you to recipes relevant to building different types of applications, such as ASP.NET MVC or WPF applications.
To complete the recipes in this book, you'll need the following tools:
Windows XP or later versions.
Visual Studio 2008 or later versions.
Microsoft SQL Server 2008 Express edition or later versions.
Chapter 5 requires NHibernate Profiler. A free, 30 day trial version is available on the web at http://nhprof.com.
This book is written for NHibernate users at all levels of experience. Examples are written in C# and XML. Some basic knowledge of SQL is needed.
Beginners will learn several techniques for each of the four core NHibernate tasks – mapping, configuration, session & transaction management, and querying – and which techniques fit best with various types of applications. In short, you will be able to build an application using NHibernate.
Intermediate level readers will learn how to best implement enterprise application architecture patterns using NHibernate, leading to clean, easy-to-understand code, and increased productivity.
In addition to new v3.0 features, advanced readers will learn creative ways to extend NHibernate core, as well as techniques using the NHibernate search, shards, spatial, and validation projects.
In this book, you will 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: Create a new class library project called EncryptedStringExample
where EncryptedStringExample is the code word in text.
A block of code is set as follows:
public interface IEncryptor
{
string Encrypt(string plainText);
string Decrypt(string encryptedText);
string EncryptionKey { get; set; }
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
using System.Collections.Generic;
namespace Eg.Core
{
public class Movie : Product
{
public virtual string Director { get; set; }
public virtual IList
}
}
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: clicking on the Next button moves you to the next screen
.
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 <feedback@packtpub.com>, 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, see our author guide on www.packtpub.com/authors.
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 this book
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
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 http://www.packtpub.com/support, 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 http://www.packtpub.com/support.
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 <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
In this chapter, we will cover the following topics:
Mapping a class with XML
Creating class hierarchy mappings
Mapping a one-to-many relationship
Setting up a base entity class
Bidirectional one-to-many class relationships
Handling versioning and concurrency
Creating mappings fluently
Mapping with ConfORM
NHibernate is a popular, mature, open source object / relational mapper (ORM) based on Java's Hibernate project. ORMs, such as LINQ to SQL, Entity Framework, and NHibernate, translate between the database's relational model of tables, columns, and keys to the application's object model of classes and properties.
The NHibernate homepage, http://NHForge.org, contains blog posts, a wiki, the complete reference documentation, and a bug tracker. Support is available through the very active nhusers Google group at http://groups.google.com/group/nhusers. The NHibernate source code is hosted on SourceForge at http://sourceforge.net/projects/nhibernate/. Precompiled binaries of NHibernate releases are also available on SourceForge.
Mapping a class with XML
The suggested first step in any new NHibernate application is mapping the model. In this first example, I'll show you how to map a simple product class.
Before we begin mapping, let's get our Visual Studio solution set up. Follow these steps to set up your solution with NHibernate binaries and schemas.
Download the NHibernate 3.0 binaries from SourceForge at http://sourceforge.net/projects/nhibernate/files/. The filename should be NHibernate-3.0.0.GA-bin.zip, perhaps with a slightly different version number.
In Visual Studio, create a new C# class library project named Eg.Core with a directory for the solution named Cookbook.
Delete the Class1.cs file.
In the Solution Explorer, right-click on the Cookbook solution and select Open Folder in Windows Explorer. This will open an Explorer window to the Cookbook directory.
Inside the Cookbook folder, create a new folder named Lib.
Extract the following files from the NHibernate 3 binaries ZIP to the Lib folder:
All files in the Required_Bin folder
All files in the Required_For_LazyLoading\Castle folder
Back in Visual Studio, right-click on the Solution, and select Add | New Solution Folder.
Name the folder Schema.
Right-click on the Schema folder, and select Add | Existing Item.
Browse to theLib folder, and
This action might not be possible to undo. Are you sure you want to continue?