Book Image

Learning NHibernate 4

Book Image

Learning NHibernate 4

Overview of this book

Table of Contents (18 chapters)
Learning NHibernate 4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Connecting the object-oriented world of .NET to the relational world of databases has always been a fiddly issue. With the onset of ORMs, such as NHibernate, developers have got some relief in this area. However, using NHibernate without understanding its core features, and how they work, can always lead to more fiddly code and frustration. Learning how to use NHibernate in practical scenarios with the help of proven patterns and techniques goes a long way to building a robust data access layer. Knowing the best practices of designing a data access layer with NHibernate, before you start your next project, will help you to avoid any problems and deliver a successful project.

What this book covers

Chapter 1, Introduction to NHibernate, provides a view of NHibernate from 10,000 feet above and touches upon topics such as what an ORM is and why developers should use it. New features of NHibernate 4.0 are examined in this chapter along with the basic building blocks of NHibernate.

Chapter 2, Let's Build a Simple Application, describes a problem statement and builds a very simple domain model, so that we have a set of known business requirements to refer to in the rest of the book. This chapter also covers different software and tools that we will use throughout the book.

Chapter 3, Let's Tell NHibernate About Our Database, takes a deep dive into one of the building blocks of NHibernate –– mapping. The chapter starts with a brief introduction to the different mechanisms of mapping supported by NHibernate. The rest of the chapter goes into the details of mapping classes, properties, identifiers, associations, and inheritance hierarchies. In this chapter, the domain model defined in Chapter 2, Let's Build a Simple Application, is mapped to an appropriate database schema.

Chapter 4, NHibernate Warm-up, walks through the configuration of NHibernate. The chapter starts with a discussion on the different ways of configuring NHibernate and the minimal configurations required to get it up and running. Many important, but optional, configurations that include caching, session context, batch size, and so on, are covered next. The chapter ends with a discussion on generating database creation and updating scripts using NHibernate mappings.

Chapter 5, Let's Store Some Data into the Database, in a nutshell covers the NHibernate API that saves data in database. Beyond this, this chapter covers important concepts such as transactions, flush modes, cascades, and inverse collections. This chapter explains how transitive persistence works in different scenarios. Entity equality and its implementation in the context of NHibernate is provided in this chapter.

Chapter 6, Let's Retrieve Some Data from the Database, as the name suggests, talks about retrieving data from the database using the different querying methods supported by NHibernate. The book stresses using LINQ but other methods, namely native SQL, HQL, Criteria API and QueryOver, are also introduced and covered in detail wherever required. The chapter goes into the details of important concepts such as joins, lazy loading, eager fetching, and polymorphic queries. Basic querying requirements such as sorting and ordering the results are explained in this chapter.

Chapter 7, Optimizing the Data Access Layer, talks about making the NHibernate code more efficient by making use of techniques such as batching, different fetching strategies, and avoiding "select N+1" and eager fetching.

Chapter 8, Using NHibernate in a Real-world Application, introduces some architectural principles such as onion architecture and dependency injection that will help in building a robust data access layer using NHibernate in production code. This chapter covers important concepts, such as unit of work and session per request along with their implementation in NHibernate. Repository pattern, the most commonly used pattern for abstracting the low level details of data access code, is also covered in this chapter.

Chapter 9, Advanced Data Access Patterns, begins with a discussion on the shortcomings of repository pattern. The chapter then introduces two data access patterns, namely specification pattern and query object pattern, which address the shortcomings of repository pattern.

Chapter 10, Working with Legacy Database, goes into the NHibernate features that come handy in legacy database situations –– where database schema is not ideal for the domain model at hand. The chapter talks about composite IDs, components, working with database views, stored procedures, and custom DTOs. Custom lazy loading retention is introduced, so that it can be used with DTOs when there is a chance that NHibernate's lazy loading is rendered ineffective.

Chapter 11, A Whirlwind Tour of Other NHibernate Features, talks about the features of NHibernate that are slightly advanced and are not touched upon in any of the previous chapters. Important features such as concurrency control, event system, caching, and user-defined types are covered along with practical examples of their usage.

What you need for this book

Though this book is code heavy, readers should be able to follow this book, if they have, at least, any version of Visual Studio and MS SQL Server. The book makes use of the following pieces of software:

  • Visual Studio 2013

  • SQL Server 2012 Express

  • NuGet

  • NUnit

  • SQLite

  • NHProfiler

  • ReSharper

If you are using Visual Studio 2010 or higher, you should be able to run the sample code of the book. SQL Server 2012 Express is used in the book, but any version of SQL Server up to SQL Server 2008 should work. NuGet is used to download NHibernate, NUnit and SQLite. NHProfiler is used to capture the SQL generated by NHibernate but SQL Profiler or NHibernate logging should do, if NHProfiler is not available. ReSharper is the author's favorite code refactoring companion for Visual Studio, but it's strictly optional.

Who this book is for

This book is intended for three types of developers:

  • You are a .NET developer and have never used an ORM before

  • You have used an ORM before, but are new to NHibernate

  • You have used NHibernate sparingly and believe that you have more to learn about NHibernate

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Once all of this is in place, you can just tell your ORM to save an instance of the Customer class."

A block of code is set as follows:

SELECT a_.FirstName,
  a_.LastName,
  a_.EmailAddress,
  a_.Age
FROM tblCustomer a_
WHERE a_.Age > 28 AND a_.Age < 35

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 interface IRepository<T> where T : EntityBase<T>
{
  void Save(T entity);
  void Update(int id, Employee employee);
  T GetById(int id);
  IEnumerable<T> Apply(ISpecification<T> specification);
}

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Next, we click on the Install button that appears next to NUnit."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

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 at 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

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

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 could 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/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted 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

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.