Table Of ContentNHibernate 3.0 Cookbook
70 incredibly powerful recipes for using the full
spectrum of solutions in the NHibernate ecosystem
Jason Dentler
community experience distilled
P U B L I S H I N G
BIRMINGHAM - MUMBAI
NHibernate 3.0 Cookbook
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 )
Credits
Author Editorial Team Leader
Jason Dentler Aanchal Kumar
Reviewers Project Team Leader
Fabio Maulo Priya Mukherji
Jose F. Romaniello
Project Coordinator
Gabriel Nicolas Schenker Prasad Rai
Tuna Toksoz
Proofreader
Acquisition Editor Clyde Jenkins
Chaitanya Apte
Graphics
Development Editor Nilesh Mohite
Rakesh Shejwal
Production Coordinator
Technical Editor Kruthika Bangera
Paramanand N. Bhat
Cover Work
Indexer Kruthika Bangera
Tejal Daruwale
About the Author
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.
About the Reviewers
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.
Table of Contents
Preface 1
Chapter 1: Models and Mappings 5
Introduction 5
Mapping a class with XML 6
Creating class hierarchy mappings 13
Mapping a one-to-many relationship 17
Setting up a base entity class 24
Handling versioning and concurrency 28
Creating mappings fluently 31
Mapping with ConfORM 34
Bidirectional one-to-many class relationships 39
Mappings enumerations 43
Creating class components 45
Chapter 2: Configuration and Schema 47
Introduction 47
Configuring NHibernate with App.config 47
Configuring NHibernate with hibernate.cfg.xml 54
Configuring NHibernate with code 56
Configuring NHibernate with Fluent NHibernate 58
Configuring NHibernate using ConfORM Mappings 60
Configuring NHibernate logging 63
Reducing application startup time 66
Generating the database 69
Scripting the database 71
Using NHibernate Schema Tool 72
Table of Contents
Chapter 3: Sessions and Transactions 75
Introduction 75
Setting up session per web request 76
Setting up session per presenter 78
Creating a session ASP.NET MVC action filter 86
Creating a Transaction ASP.NET MVC action filter 92
Using the Conversation per Business Transaction pattern 94
Using session.Merge 101
Using session.Refresh 103
Using stateless sessions 105
Using dictionaries as entities 107
Using NHibernate with TransactionScope 112
Chapter 4: Queries 119
Introduction 119
Using Criteria Queries 125
Using QueryOver 130
Using QueryOver projections and aggregates 133
Using MultiCriteria 138
Using the Hibernate Query Language 140
Using MultiQuery 147
Using Named Queries 149
Using Futures 152
Eager loading child collections 155
Using LINQ to NHibernate 159
Using Detached Queries 162
Using HQL for bulk data changes 163
Chapter 5: Testing 167
Introduction 167
Using NHibernate Profiler 167
Fast testing with SQLite in-memory database 172
Preloading data with SQLite 179
Using the Fluent NHibernate Persistence Tester 182
Using the Ghostbusters test 184
Chapter 6: Data Access Layer 191
Introduction 191
Transaction Auto-wrapping for the data access layer 191
Setting up an NHibernate Repository 194
Using Named Queries in the data access layer 198
Using ICriteria in the data access layer 205
ii
Table of Contents
Using Paged Queries in the data access layer 208
Using LINQ Specifications in the data access layer 212
Chapter 7: Extending NHibernate 217
Introduction 217
Creating an encrypted string type 217
Using well-known instance type 225
Using dependency injection with entities 231
Creating an audit-event listener 235
Creating and changing stamping entities 239
Generating trigger-based auditing 244
Setting MS Sql's Context Info 247
Using dynamic connection strings 253
Chapter 8: NHibernate Contribution Projects 255
Introduction 255
Configuring the cache 255
Configuring the cache with code 259
Property validation with attributes 262
Creating validator classes 268
Using the Burrows framework 272
Setting up full-text search 280
Sharding databases for performance 288
Using NHibernate Spatial 295
Appendix: Menu 303
ASP.NET MVC web applications 303
ASP.NET Web Forms applications 304
WPF and WinForms applications 305
Index 307
iii