NHibernate 3 Beginner's Guide

NHibernate 3 Beginner's Guide
eBook: $26.99
Formats: PDF, PacktLib, ePub and Mobi formats
save 15%!
Print + free eBook + free PacktLib access to the book: $71.98    Print cover: $44.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Table of Contents
Sample Chapters
  • Incorporate robust, efficient data access into your .Net projects
  • Reduce hours of application development time and get better application architecture and performance
  • Create your domain model first and then derive the database structure automatically from the model
  • Test, profile, and monitor data access to tune the performance and make your applications fly
  • Clear, precise step-by-step directions to get you up and running quickly

Book Details

Language : English
Paperback : 368 pages [ 235mm x 191mm ]
Release Date : August 2011
ISBN : 1849516022
ISBN 13 : 9781849516020
Author(s) : Dr. Gabriel Nicolas Schenker, Aaron Cure
Topics and Technologies : All Books, Application Development, Beginner's Guides, Open Source

Table of Contents

Chapter 1: First Look
Chapter 2: A First Complete Sample
Chapter 3: Creating a Model
Chapter 4: Defining the Database Schema
Chapter 5: Mapping the Model to the Database
Chapter 6: Sessions and Transactions
Chapter 7: Testing, Profiling, Monitoring, and Logging
Chapter 8: Configuration
Chapter 9: Writing Queries
Chapter 10: Validating the Data to Persist
Chapter 11: Common Pitfalls—Things to Avoid
Appendix: Pop Quiz Answers
  • Chapter 1: First Look
    • What is NHibernate
    • What is new in NHibernate 3.0
    • Why would I use it
    • Where do I get it
    • Is there documentation available
    • Can I get help using NHibernate
    • Is there commercial support available
    • Who uses it
    • Summary
    • Chapter 2: A First Complete Sample
      • Prepare our development environment
      • Defining a model
      • Time for action – Creating the product inventory model
      • Mapping our model
      • Time for action – Creating the mapping classes
      • Creating the database schema
      • Time for action – Creating the database
      • Creating a session factory
      • Time for action – Creating a session factory
      • Opening a session
      • Time for action – Opening a session to the database
      • Persisting objects to the database
      • Time for action – Adding a new category to the database
      • Reading from the database
      • Time for action – Loading the list of all categories from the database
      • Doing the same without NHibernate – using ADO.NET only
      • Summary
      • Chapter 3: Creating a Model
        • What is a model
        • Model first versus data first
        • Elements of a model
          • Entity
          • Value object
        • Time for action – Creating a Name value object
        • Creating an entity
        • Time for action – Creating a base entity
        • Time for action – Creating a Customer entity
        • Defining relations between entities
          • Owns or contains
          • One-to-many
          • One-to-one
          • Many-to-many
        • The order entry model
        • Time for action – Implementing an order entry model
        • Summary
        • Chapter 4: Defining the Database Schema
          • What is a database schema
            • Who owns the database
          • Time for action – Creating the OrderingSystem database
          • Laying the foundation – table layouts
          • Time for action – Creating the Categories table
          • Time for action – Defining a script to create the Products table
          • Table columns
            • Data types of table columns
          • Relations, constraints, and indices
            • Relations
            • Constraints
          • Time for action – Adding a constraint to the Product table
          • Time for action – Creating a script to add a check constraint
            • Indices
          • Time for action – Adding an index using the designer
          • Time for action – Creating a script to add an index
          • Normal form
          • Putting it all together
          • Time for action – Creating a schema for the order entry system
          • Do not use database-generated IDs
          • Views
          • What about stored procedures and triggers
          • Summary
          • Chapter 5: Mapping the Model to the Database
            • What is mapping?
            • Types of mapping
              • XML-based mapping
              • Attribute-based mapping
              • Fluent mapping
              • Mapping by convention
            • A word about lazy loading
              • Loading data on demand
              • Proxies
              • Virtual properties and methods
            • Creating database schema creation scripts
            • Fluent mapping
              • Expression trees – please explain
              • Getting started
              • Classes
              • Entity level settings
              • ID columns
              • Properties
              • References
              • Collections
              • Mapping many-to-many relations
              • Mapping value objects
            • Time for action – Mapping our domain
            • Use mapping conventions
              • ID conventions
              • Property conventions
              • Foreign key conventions
            • No mapping; is that possible?
              • Auto-mapping with Fluent NHibernate
            • Time for action – Using auto-mapping
              • Using ConfORM
            • Time for action – Using ConfORM to map our domain
            • XML mapping
              • Getting started
              • Classes
              • Properties
              • ID columns
              • One-to-many relations
              • Many-to-many relations
              • Mapping value objects
            • Time for action – Mapping a simple domain using XML
            • Summary
            • Chapter 6: Sessions and Transactions
              • What are sessions and transactions
                • Session
                • Transaction
              • The session factory
              • Creating your first session
                • Why do we call Commit?
                • Adding new data to the database
                • Reading data from the database
                • Get versus Load
                • Updating existing data
                • Deleting data
              • First level cache or identity map
                • Clearing the cache
                • Refreshing entities in the cache
              • No database operation without a transaction
                • Should I use transactions when querying data?
              • NHibernate session versus database session
              • Time for action – Creating a session and doing some CRUD
              • Session management
                • Web-based applications
              • Time for action –Implementing session management for a web application
                • WinForm or WPF applications
                • Windows services
              • Unit of Work
              • Handling exception
              • Second level cache
                • Cache regions
                • Second level cache implementations
              • Time for action – Using a second level cache
              • Summary
              • Chapter 7: Testing, Profiling, Monitoring, and Logging
                • Why do we need tests?
                • What should we test?
                • What about the database?
                  • Download SQLite
                • Preparing our environment for testing
                  • Testing the mapping
                  • Testing the mapping with Fluent NHibernate
                • Time for action – Creating the base for testing
                • Time for action – Using SQLite in our tests
                  • Testing queries
                • Logging
                  • Why do we need to log?
                  • Logging with Log4Net
                • Time for action – Adding logging to our application
                  • Setting up logging for NHibernate
                • Time for action – Enable logging in NHibernate
                • Monitoring and profiling
                  • Analyzing log files
                  • Using SQL Server Profiler
                  • Monitoring and profiling with NHibernate Profiler
                • Time for action – Adding NHibernate Profiler support
                • Summary
                • Chapter 8: Configuration
                  • Why do we need a configuration?
                  • Elements of the configuration
                    • Which database do we want to use?
                    • What byte code provider and proxy factory?
                    • Where are our mappings?
                    • Do we use second level caching?
                    • Do we want to extend NHibernate?
                  • XML configuration
                  • Time for action – Configuring NHibernate using XML
                  • Configuring NHibernate in code
                  • Time for action – Configuring NHibernate in code
                  • Fluent configuration
                    • Configuring NHibernate with Loquacious
                  • Time for action – Using Loquacious to configure NHibernate
                    • Configuring NHibernate with Fluent NHibernate
                  • Convention over configuration
                  • Summary
                  • Chapter 9: Writing Queries
                    • How can we get to our data?
                    • The LINQ to NHibernate provider
                      • Defining the root of our query
                      • Limiting the number of records returned
                      • Filtering a set of records
                      • Mapping a set of records
                      • Sorting the resulting set
                      • Grouping records
                      • Forcing a LINQ query to execute immediately
                      • Changing from querying the database to querying in-memory objects
                    • Creating a report using LINQ to NHibernate
                    • Time for action – Preparing the system
                    • Time for action – Creating the reports
                    • Criteria queries
                      • Untyped criteria queries
                      • Strongly-typed criteria queries
                    • Time for action – Using QueryOver to retrieve data
                    • Hibernate Query Language
                    • Lazy loading properties
                    • Executing multiple queries in a batch
                    • Eager loading versus lazy loading
                    • Bulk data changes
                    • Summary
                    • Chapter 10: Validating the Data to Persist
                      • What is validation and why is it so important?
                      • Who owns the database?
                      • Why, what, and where do we validate?
                        • Why validate?
                        • What data?
                        • Where to validate?
                      • Validating single properties
                        • Configuring the validator
                        • Defining validation rules
                        • Fluently configure validation rules
                        • Enforcing validation
                      • Time for action – Using property validation
                      • Validating complex business rules
                        • Enforcing always valid entities
                        • Using validation classes
                      • Time for action – Validating user input
                      • What to do if we don't own the database?
                      • Summary
                      • Chapter 11: Common Pitfalls—Things to Avoid
                        • Requesting the obvious
                        • Wrong mapping for read-only access
                        • Blindly relying on NHibernate
                        • Using implicit transactions
                        • Using database-generated IDs
                        • Using LINQ to NHibernate the wrong way
                        • The trouble with lazy loading
                          • The select (n+1) problem
                          • Accessing lazy loaded parts after the session is closed
                          • Did I just load the whole database?
                        • Using one model for read and write operations
                          • CQRS
                        • Phantom updates
                        • Time for action – Causing a phantom update
                        • Using NHibernate to persist any type of data
                        • Summary
                        • Chapter 4
                          • Defining the Database Schema
                        • Chapter 5
                          • Mapping the Model to the Database
                        • Chapter 6
                          • Sessions and Transactions
                        • Chapter 7
                          • Testing, Profiling, Monitoring, and Logging
                        • Chapter 8
                          • Configuration
                        • Chapter 9
                          • Writing Queries
                        • Chapter 10
                          • Validating the Data to Persist

                          Dr. Gabriel Nicolas Schenker

                          Gabriel N. Schenker started his career as a physicist. Following his passion and interest in stars and the universe he chose to write his Ph.D. thesis in astrophysics. Soon after this he dedicated all his time to his second passion, writing and architecting software. Gabriel has since been working for over 12 years as an independent consultant, trainer, and mentor mainly on the .NET platform. He is currently working as chief 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 hospitals and universities throughout the US and in many other countries around the world. Gabriel is passionate about software development and tries to make the life of 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 has also been a reviewer for the bestselling NHibernate 3 Cookbook. Gabriel is married and father of four children and during his spare time likes hiking in the mountains, cooking and reading.

                          Aaron Cure

                          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.
                          Sorry, we don't have any reviews for this title yet.

                          Code Downloads

                          Download the code and support files for this book.

                          Submit Errata

                          Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


                          - 5 submitted: last submission 08 Nov 2013

                          Errata type: Code | Page number: 158 | Errata date: 31 October 11

                          In point #14 instead of: returntype.Namespace == typeof(Customer).Namespace;

                          it should read: return type.Namespace == typeof(Customer).Namespace;


                          Errata type: Typo | Page number: 82 | Errata date: 25 September 11

                          Time for action:

                          Step 2 Table name Product instead of Products in OBJECT_ID Similarly in: DROP INDEX ... ON Product (correct: ON Products)

                          Step 3 CREATE ... ON Product (Name ASC) (CORRECT: CREATE ... ON Products (Name ASC)


                          Errata type: Code | Page number: 78 | Errata date: 25 September 11

                          Time for action: step 2 Time for action / Point 2

                          The line that reads: ALTER TABLE Product DROP CONSTRAINT CK_Products_ReorderLevel

                          should read: ALTER TABLE Products DROP CONSTRAINT CK_Products_ReorderLevel


                          Errata type: Code | Page number: 96

                          Near top of page it states:
                             <property name="Name" type="Int32"/>

                          Typically, a Name field will not have an integer type. It should be:
                             <property name="Name" type="String"/>

                          Errata type: Typo | Page number: 51

                          "...together with its base class and the Name value object, which is used as 
                          a type of the CustomerIdentifier property of the Customer class."

                          Should be:

                          "...together with its base class and the Name value object, which is used as 
                          a type of the CustomerName property of the Customer class."

                          Errata type: Typo | Page number: 106

                          "..we add a reference to Fluent NHibernate and to NHibernate, as shown in the following screenshot."

                           Should be:

                          "..we add a reference to Fluent NHibernate, which is shown in the following screenshot, also and to NHibernate."

                          Sample chapters

                          You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

                          Frequently bought together

                          NHibernate 3 Beginner's Guide +    Programming Microsoft Dynamics® NAV 2013 =
                          50% Off
                          the second eBook
                          Price for both: €36.00

                          Buy both these recommended eBooks together and get 50% off the cheapest eBook.

                          What you will learn from this book

                          • Create a domain model
                          • Learn different techniques to map the domain model to the underlying database
                          • Build the database from your model automatically
                          • Use session and transactions to persist and retrieve data
                          • Efficiently query the database by using LINQ to NHibernate and HQL
                          • Configure your system for use of NHibernate in a clear and concise way
                          • Write unit and integration tests for your data access layer
                          • Learn about the common pitfalls that should be avoided
                          • Implement data validation on the entity level
                          • Monitor and profile your data access

                          In Detail

                          Ideally, we would want to persist the objects our application uses and produces AS IS, without having to first transform them in complex ways. NHibernate is a framework that provides us with an object-oriented access to a relational database without having to write SQL and with little or no database-specific data access code. Definitely, if you are a .NET developer, knowing more about NHibernate will simplify and reduce your efforts in developing .Net applications.NHibernate 3 Beginner's Guide introduces Nhibernate with step-by-step examples, and is the easiest way to learn about bridging the gap between object-oriented .NET applications and the relational database that stores the application's data. It is a beginner's guide to NHibernate that starts from scratch. Successive chapters build upon earlier concepts, while the sample code presents various ways to accomplish typical data access tasks.

                          NHibernate 3 Beginner's Guide examines all of the topics required to get a functional data access layer implemented while writing the least amount of code possible, presenting options along the way to handle particular edge cases or situations as they arise. The book begins with an introduction to NHIbernate 3 and then moves on to creating the development environment. Then it teaches you how to create a model, define a database schema, and map the model to the database then covers sessions and transactions. This is succeeded by testing, profiling, and configuration, validation of data and writing queries. Finally, we wrap up with notes on the common pitfalls that you should avoid.

                          Once you complete reading the book, you will have gained the skills and knowledge to incorporate NHibernate into your own applications.

                          An easy-to-follow guide that will show you how to connect the NHibernate object-relational mapper to your projects to create a rich, efficient, object-oriented data access layer with little or no additional work


                          This is a beginner’s guide with comprehensive step-by-step instructions. There are appropriate screenshots throughout the book and plenty of code, which is explained in a well-thought-out format.

                          Who this book is for

                          If you are a new or seasoned developer of .NET web or desktop applications who is looking for a better way to access database data, then this book is for you. 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. Absolutely no knowledge of NHibernate is required to read this book.

                          Code Download and Errata
                          Packt Anytime, Anywhere
                          Register Books
                          Print Upgrades
                          eBook Downloads
                          Video Support
                          Contact Us
                          Awards Voting Nominations Previous Winners
                          Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
                          Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software