Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
NHibernate 4.x Cookbook
NHibernate 4.x Cookbook

NHibernate 4.x Cookbook: Over 90 incredible and powerful recipes to help you efficiently use NHibernate in your application , Second Edition

Arrow left icon
Profile Icon Jason Dentler Profile Icon Zaytsev Profile Icon Darshan Joshi Profile Icon Liljas
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Jan 2017 448 pages 2nd Edition
eBook
NZ$14.99 NZ$64.99
Paperback
NZ$80.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jason Dentler Profile Icon Zaytsev Profile Icon Darshan Joshi Profile Icon Liljas
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Jan 2017 448 pages 2nd Edition
eBook
NZ$14.99 NZ$64.99
Paperback
NZ$80.99
Subscription
Free Trial
eBook
NZ$14.99 NZ$64.99
Paperback
NZ$80.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

NHibernate 4.x Cookbook

Chapter 1. The Configuration and Schema

In this chapter, we will cover the following recipes:

  • Installing NHibernate
  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with App.config or Web.config
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate
  • Configuring NHibernate logging
  • Generating the database
  • Scripting the database
  • Updating the database
  • Using NHibernate schema tool

Introduction

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://nhibernate.info, contains blog posts, 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 GitHub at http://github.com/nhibernate/nhibernate-core. Precompiled binaries of NHibernate releases are also available on SourceForge and through NuGet at http://nuget.org/packages/NHibernate.

NHibernate provides an incredible number of configuration options and settings. The recipes in this chapter demonstrate several methods for configuring NHibernate and generating the necessary database schema.

Installing NHibernate

Before we begin, let's get our Visual Studio solution and database set up. The following information will get you up and started with NHibernate.

Getting ready

  1. Install Microsoft SQL Server 2012 Express (or a newer version) on your PC, using the default settings.
  2. Create a blank database named NHCookbook.

How to do it...

  1. In Visual Studio, create a new C# class library project named Eg.Core with a directory for the solution named Cookbook.
  2. Delete the Class1.cs file.
  3. In the Solution Explorer, right click the References node in the Eg.Core project and select Manage NuGet Packages. In the top navigation of the now-opened NuGet Package Manager, make sure Browse is selected. Enter the word NHibernate in the search box and wait for the results to show up:
    How to do it...
  4. Select the NHibernate package in the search results and click Install. This will install NHibernate and all required dependencies.
  5. Add a new class named TestClass, to the Eg.Core project:
    public class TestClass
    {
      public virtual int Id { get; set; }
      public virtual string Name { get; set; }
    }

There's more…

Instead of using the graphical package manager, you can use the Package Manager Console. It provides a faster way to install or update NuGet packages. To open the Package Manager Console simply click Tools | NuGet Package Manager | Package Manager Console. In the opened window you can simply write the following:

Install-Package NHibernate -Project Eg.Core

This will produce the same effect as the main recipe.

Configuring NHibernate with hibernate.cfg.xml

NHibernate offers several methods for configuration and a number of configuration settings.

In this recipe, we will show you how to configure NHibernate using the hibernate.cfg.xml configuration file, with a minimal number of settings to get your application up and running quickly. The recipe also forms the base for several other recipes in this chapter.

Getting ready

  1. Complete the steps from the Installing NHibernate recipe in this chapter.
  2. Add a console application project to your solution called ConfigByXml.
  3. Set it as the Startup project for your solution.
  4. Install NHibernate to ConfigByXml project using the NuGet Package Manager Console.
  5. In ConfigByXml, add a reference to the Eg.Core project.

How to do it...

  1. Add an XML file named hibernate.cfg.xml with the following contents:
    <?xml version="1.0" encoding="utf-8"?>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <session-factory>
        <property name="dialect">
          NHibernate.Dialect.MsSql2012Dialect, NHibernate
        </property>
        <property name="connection.connection_string">
          Server=.\SQLEXPRESS; Database=NHCookbook; 
          Trusted_Connection=SSPI
        </property>
        <property name="adonet.batch_size">
          100
        </property>
      </session-factory>
    </hibernate-configuration>
  2. On the Solution Explorer tab, right-click on hibernate.cfg.xml and select Properties.
  3. Change Copy to Output Directory property from Do not copy to Copy if newer.
  4. Open Program.cs and add using NHibernate.Cfg; to the beginning of the file
  5. Add the following code to the Main method:
    var nhConfig = new Configuration().Configure();
    var sessionFactory = nhConfig.BuildSessionFactory();
    Console.WriteLine("NHibernate Configured!");
    Console.ReadKey();
  6. Build and run your application. You will see the text NHibernate Configured!

How it works...

The connection string we've defined points to the NHCookbook database running under the local Microsoft SQL Server.

Next, we define a few properties that tell NHibernate how to behave.

The dialect property specifies a dialect class that NHibernate uses to build SQL syntax specific to a Relational Database Management System (RDBMS). We're using the Microsoft SQL 2012 dialect. Additionally, most dialects set intelligent defaults for other NHibernate properties, such as connection.driver_class.

The connection.connection_string_name property references our connection string by name.

By default, NHibernate will send a single SQL statement and wait for a response from the database. When we set the adonet.batch_size property to 100, NHibernate will group up to 100 SQL INSERT, UPDATE, and DELETE statements in a single ADO.NET command and send the whole batch at once. In effect, the work of 100 round trips to the database is combined in one. Because a roundtrip to the database is, at best, an out-of-process call, and at worst, a trip through the network or even the Internet, this can improve performance significantly. Batching is currently supported when targeting Microsoft SQL Server, Oracle, or MySQL.

We change Copy to Output directory to ensure that our hibernate.cfg.xml file is copied to the build output directory.

There's more...

By default, NHibernate looks for its configuration in the hibernate.cfg.xml file. However, the Configure method has three extra overloads, which can be used to provide configuration data from other sources, such as:

  • From a different file:
    var cfgFile = "cookbook.cfg.xml"; 
    var nhConfig = new Configuration().Configure(cfgFile);
  • From a file embedded into an assembly file:
    var assembly = GetType().Assembly;
    var path = "MyApp.cookbook.cfg.xml"; 
    var nhConfig = new Configuration().Configure(assembly, path);
  • From an XmlReader:
    var doc = GetXmlDocumentWithConfig();
    var reader = new XmlNodeReader (doc);
    var nhConfig = new Configuration().Configure(reader);

NHibernate architecture

There are several key components to an NHibernate application, as shown in this diagram:

NHibernate architecture

On startup, an NHibernate application builds a Configuration object. In this recipe, we build the configuration from settings in the hibernate.cfg.xml file. The Configuration object is responsible for loading mappings, investigating the object model for additional information, building the mapping metadata, and finally building a session factory. Building the session factory is a rather resource intensive operation, and is normally only done once, when the application starts up.

A session represents a Unit of Work in the application. Martin Fowler defines a Unit of Work as something that "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems". An NHibernate session tracks changes to entities and writes those changes back to the database all at once. In NHibernate, this process of waiting to write to the database is called transactional write-behind. In addition, the session is the entry point to much of the NHibernate API. More information about the Unit of Work pattern is available at http://martinfowler.com/eaaCatalog/unitOfWork.html and in Fowler's book, Patterns of Enterprise Application Architecture. A session factory is responsible for creating sessions.

The session acts as an intermediary between our application and several key NHibernate components. A typical application will not interact with these components directly, but understanding them is critical to understanding NHibernate. Unlike a session factory, building a session is very cheap.

A dialect is used to build correct SQL syntax for a specific RDBMS. For example, in some versions of Microsoft SQL Server, we begin a select statement with SELECT TOP 20 to specify a maximum result set size. Only 20 rows will be returned. Similarly, to perform this operation in SQLite, we append LIMIT 20 to the end of the select statement. Each dialect provides the necessary SQL syntax string fragments and other information to build correct SQL strings for the chosen RDBMS.

A driver is responsible for building a Batcher, creating IDbConnection and IDbCommand objects, and preparing those commands.

A connection provider is simply responsible for opening and closing database connections.

A batcher manages the batch of commands to be sent to the database and the resulting data readers. Currently, only the SqlClientDriver, OracleDataDriver, and MySqlDataDriver support batching. The drivers that don't support batching provide a NonBatchingBatcher to manage IDbCommands and IDataReaders and simulate the existence of a single logical batch of commands.

NHibernate properties

Here are some of the commonly used NHibernate properties:

Property name

Description

connection.provider

This property is a provider class to open and close database connections.

connection.driver_class

This property is specific to the RDBMS used, and is typically set by the dialect.

connection.connection_string

This property is a database connection string.

connection.connection_string_name

This property is the name of connection string in <connectionStrings> element.

connection.isolation

This property is at the transaction isolation level.

dialect

This property is required. A class to build RDBMS-specific SQL strings. Typically, this is one of the many dialects from the NHibernate.Dialect namespace.

show_sql

This is property is a Boolean value. It is set to true to log all SQL statements to Console.Out. Alternatively, log4net may be used to log to other locations.

current_session_context_class

This property is a class to manage contextual sessions. This is covered in depth in Chapter 3, Sessions and Transactions.

query.substitutions

This property is a comma-separated list of translations to perform on query strings. For example, True=1, Yes=1, False=0, No=0.

sql_exception_converter

This property is a class to convert RDBMS-specific ADO.NET Exceptions to custom exceptions.

prepare_sql

This property is a Boolean value. Prepares SQL statements and caches the execution plan for the duration of the database connection.

command_timeout

This property is the number of seconds to wait for a SQL command to complete before timing out.

adonet.batch_size

This property is the number of SQL commands to send at once before waiting for a response from the database.

generate_statistics

This property enables tracking of some statistical information, such as the number of queries executed and entities loaded.

format_sql

This property adds line endings for easier-to-read SQL statements.

Additional information about each of these settings is available in the reference documentation at http://nhibernate.info/doc/nhibernate-reference/index.html.

Dialects and drivers

Many dialects set other NHibernate properties to sensible default values, including, in most cases, the connection.driver_class. NHibernate includes the following dialects in the NHibernate.Dialect namespace and drivers in the NHibernate.Driver namespace:

RDBMS

Dialect(s)

Driver(s)

Microsoft SQL Server

MsSql2012Dialect

MsSql2008Dialect

MsSqlAzure2008Dialect

MsSql2005Dialect

MsSql2000Dialect

MsSql7Dialect

MsSqlCE40Dialect

MsSqlCEDialect

SqlClientDriver

SqlServerCEDriver

Oracle

Oracle12cDialect

Oracle10gDialect

Oracle9iDialect

Oracle8iDialect

OracleLiteDialect

OracleClientDriver

OracleDataClientDriver

OracleLiteDataDriver

OracleManagedDataClientDriver

MySql

MySQL55Dialect

MySQL5Dialect

MySQL55InnoDBDialect

MySQL5InnoDBDialect

MySQLDialect

MySqlDataDriver

DotConnectMySqlDriver

PostgreSQL

PostgreSQLDialect

PostgreSQL81Dialect

PostgreSQL82Dialect

NpgsqlDriver

DB2

DB2Dialect

Db2400Dialect

DB2Driver

DB2400Driver

Informix

InformixDialect

InformixDialect0940

InformixDialect1000

IfxDriver

Sybase

SybaseASA9Dialect

SybaseASE15Dialect

SybaseSQLAnywhere10Dialect

SybaseSQLAnywhere11Dialect

SybaseSQLAnywhere12Dialect

SybaseAsaClientDriver

SybaseAseClientDriver

SybaseSQLAnywhereDotNet4Driver

SybaseSQLAnywhereDriver

Firebird

FirebirdDialect

FirebirdClientDriver

SQLite

SQLiteDialect

SQLite20Driver

Ingres

IngresDialect

Ingres9Dialect

IngresDriver

See also

  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate

Configuring NHibernate with App.config or Web.config

Another common method for configuring NHibernate uses a .NET configuration file. In this recipe, we will show you how to configure NHibernate using App.config or Web.config files, to provide an identical configuration to the previous recipe.

Getting ready

  1. Complete the steps in the Installing NHibernate recipe.
  2. Add a console application project named ConfigByAppConfig to your solution.
  3. Set it as the Startup project for your solution.
  4. Install NHibernate to the ConfigByAppConfig project using the NuGet Package Manager Console.
  5. In ConfigByAppConfig, add a reference to the Eg.Core project.
  6. Add an App.config file to your project.

How to do it…

  1. Open the App.config file.
  2. Declare a section for the NHibernate configuration, as shown here:
    <configSections>
      <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, 
    NHibernate" />
    </configSections>
  3. Add a connectionStrings section with a connection string:
    <connectionStrings>
      <add name="db" connectionString="Server=.\SQLEXPRESS; Database=NHCookbook; Trusted_Connection=SSPI"/>
    </connectionStrings>
  4. Add your hibernate-configuration section:
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <session-factory>
        <property name="dialect">
          NHibernate.Dialect.MsSql2008Dialect, NHibernate
        </property>
        <property name="connection.connection_string_name">
          db
        </property>
        <property name="adonet.batch_size">
          100
        </property>
      </session-factory>
    </hibernate-configuration>
  5. Your completed App.config file should look similar to this:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, 
          NHibernate" />
      </configSections>
      <connectionStrings>
        <add name="db" connectionString="Server=.\SQLEXPRESS; Database=NHCookbook; Trusted_Connection=SSPI" />
      </connectionStrings>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <session-factory>
        <property name="dialect">
          NHibernate.Dialect.MsSql2008Dialect, NHibernate
        </property>
        <property name="connection.connection_string_name">
          db
        </property>
        <property name="adonet.batch_size">
          100
        </property>
      </session-factory>
    </hibernate-configuration>
    </configuration>
  6. Open Program.cs and add using NHibernate.Cfg; to the beginning of the file.
  7. In the Main method, add the following code to configure NHibernate:
    var nhConfig = new Configuration().Configure();
    var sessionFactory = nhConfig.BuildSessionFactory();
    Console.WriteLine("NHibernate Configured!");
    Console.ReadKey();
  8. Build and run your application. You will see the text NHibernate Configured!

How it works…

This recipe works in the same way as the previous recipe. However, in this recipe, we have moved the hibernate-configuration element from the hibernate.cfg.xml file to App.config. The connection.connection_string_name property references our connection string named db. We can name the connection string anything we like, as long as this property matches the connection string's name.

There's more…

An ASP.NET application's Web.config uses the common .NET framework configuration platform and has the same structure as App.config. You can therefore use the same technique to configure NHibernate in a web application.

See also

  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate

Configuring NHibernate with code

You can also configure NHibernate entirely in code. In this recipe, we'll show you how to do just that.

Getting ready

  1. Complete the steps in the Installing NHibernate recipe.
  2. Add a console application project to your solution called ConfigByCode.
  3. Set it as the Startup project for your solution.
  4. Install NHibernate to ConfigByCode project using NuGet Package Manager Console.
  5. In ConfigByCode, add a reference to the Eg.Core project.

How to do it…

  1. Add an App.config file with this configuration:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings>
        <add name="db" connectionString="Server=.\SQLEXPRESS; Database=NHCookbook; Trusted_Connection=SSPI" />
      </connectionStrings>
    </configuration>
  2. In Program.cs, add the following using statements:
    using NHibernate.Cfg;
    using NHibernate.Dialect;
  3. In your Main function, add the following code to configure NHibernate:
    var nhConfig = new Configuration().DataBaseIntegration(db =>
    {
      db.Dialect<MsSql2012Dialect>();
      db.ConnectionStringName = "db";
      db.BatchSize = 100;
    });
    var sessionFactory = nhConfig.BuildSessionFactory();
    Console.WriteLine("NHibernate Configured!");
    Console.ReadKey();
  4. Build and run your application. You should see the text NHibernate Configured!

How it works…

In this recipe, we create an NHibernate configuration using methods in the NHibernate.Cfg namespace. These methods offer full type safety and improved discoverability over code configurations in the previous version of NHibernate.

We specify dialect, connection.connection_string_name, and adonet.batch_size with the DatabaseIntegration method. Finally, we build a session factory using the BuildSessionFactory method.

There's more...

Notice that we are still referencing the db connection string defined in our App.config file. If we wanted to eliminate the App.config file entirely, we could hardcode the connection string with this code:

db.ConnectionString = @"Connection string here...";

This, however, is completely inflexible, and will require a full recompile and redeployment for even a minor configuration change.

See also

  • Configuring NHibernate with App.config or Web.config
  • Configuring NHibernate with XML
  • Configuring NHibernate with Fluent NHibernate

Configuring NHibernate with Fluent NHibernate

The third-party Fluent NHibernate library has its own syntax to configure NHibernate. In this recipe, we'll show you how to configure NHibernate using this syntax.

Getting ready

  1. Complete the steps in Installing NHibernate recipe.
  2. Add a console application project to your solution called ConfigByFNH.
  3. Set it as the Startup project for your solution.
  4. Install NHibernate to the ConfigByFNH project using NuGet Package Manager Console.
  5. Install the package FluentNHibernate to ConfigByFNH project using NuGet Package Manager Console.
  6. In ConfigByFNH, add a reference to the Eg.Core project.

How to do it…

  1. Add an App.config file with this configuration:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings>
        <add name="db" connectionString="Server=.\SQLEXPRESS; Database=NHCookbook; Trusted_Connection=SSPI" />
      </connectionStrings>
    </configuration>
  2. In Program.cs, add the following using statements:
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
  3. In the Main method, add this code:
    var config = MsSqlConfiguration.MsSql2012
      .ConnectionString(connstr => connstr.FromConnectionStringWithKey("db"))
      .AdoNetBatchSize(100);
    var nhConfig = Fluently.Configure()
      .Database(config)
      .BuildConfiguration();
    var sessionFactory = nhConfig.BuildSessionFactory();
    Console.WriteLine("NHibernate configured fluently!");
    Console.ReadKey();
  4. Build and run your application. You should see the text NHibernate configured fluently!

How it works…

Our fluent configuration can be broken down into three parts. First, we configure these properties:

  1. We set the dialect property to MsSql2012Dialect when we use the MsSql2012 static property of MsSqlConfiguration.
  2. The connection.connection_string_name object is set to db with a call to FromConnectionStringWithKey.
  3. We set adonet.batch_size to 100 with a call to AdoNetBatchSize.

Next, from the fluent configuration, we build a standard NHibernate configuration. Finally, we build a session factory using the BuildSessionFactory method.

See also

  • Configuring NHibernate with App.config or Web.config
  • Configuring NHibernate with XML
  • Configuring NHibernate with code

Configuring NHibernate logging

NHibernate has a very extensible logging mechanism, and provides a log4net log provider out of the box. The log4net library is a highly customizable, open source logging framework. In this recipe, we'll show you a simple log4net configuration to log important NHibernate events to the Visual Studio debug output window.

Getting ready

Complete the earlier Configuring NHibernate with App.config or Web.config recipe.

How to do it...

  1. Install log4net using NuGet Package Manager.
  2. Open your application configuration file.
  3. Inside the configSections element, declare a section for the log4net configuration:
    <section name="log4net"
    type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  4. After the hibernate configuration element, add this log4net configuration:
    <log4net>
    <appender name="trace" 
          type="log4net.Appender.TraceAppender, log4net">
      <layout type="log4net.Layout.PatternLayout, log4net">
      <param name="ConversionPattern" 
           value=" %date %level %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="trace" />
    </root>
    <logger name="NHibernate">
      <level value="INFO" />
    </logger>
    </log4net>
  5. At the beginning of your Main function, insert the following code to configure log4net:
    log4net.Config.XmlConfigurator.Configure();
  6. Run your application.
  7. Watch Visual Studio's debug output window.

How it works...

The log4net framework uses appenders, layouts, and loggers to format and control log messages from our application, including log messages from NHibernate.

Appenders define the destination for log messages. In this recipe, we've defined a trace appender, which writes our log messages to System.Diagnostics.Trace. When we debug our application, Visual Studio listens to the trace and copies each message to the debug output window.

Loggers are the source of log messages. The root element defines values for all loggers, which can be overridden using the logger element. In our configuration, we've declared that all messages should be written to the appender named trace.

In log4net, the log messages have priorities. In ascending order, they are DEBUG, INFO, WARN, ERROR, and FATAL. In our configuration, we can define a log level with one of these priorities, or with ALL or OFF. A level includes its priority and all the priorities above it. For example, a level of WARN will also log ERROR and FATAL messages. ALL is equivalent to DEBUG: all messages will be logged, and OFF suppresses all messages.

With our configuration, log4net will write messages from NHibernate with a priority of INFO, WARN, ERROR, and FATAL, and ALL messages from other sources.

There's more...

We can use log4net in our own application. Here's a simple example of what some code might look like with log4net logging:

using System.IO;
using log4net;
namespace MyApp.Project.SomeNamespace
{

    public class Foo
    {
        private static ILog log = LogManager.GetLogger(typeof(Foo));

        public string DoSomething()
        {
            log.Debug("We're doing something.");
            try
            {
                return File.ReadAllText("cheese.txt");
            }
            catch (FileNotFoundException)
            {
                log.Error("Somebody moved my cheese.txt");
                throw;
            }
        }
    }
}

We've defined a simple class named Foo. In the DoSomething() method, we write the log message, "We're doing something.", with a priority of DEBUG. Then we return the contents of the file cheese.txt. If the file doesn't exist, we log an error and throw the exception.

Because we passed in typeof(Foo) when getting the logger, the Foo logger is named MyApp.Project.SomeNamespace.Foo, similar to the type. This is the typical naming convention when using log4net.

Suppose we were no longer concerned with debug level messages from Foo, but we still wanted to know about warnings and errors. We can then redefine the log level with this simple addition to our configuration, as shown in the following code:

<logger name="MyApp.Project.SomeNamespace.Foo">
  <level value="WARN" />
</logger>

Alternatively, we can set the log level for the entire namespace or even the entire project with this configuration, as follows:

<logger name="MyApp.Project">
  <level value="WARN" />
</logger>

Using logger to troubleshoot NHibernate

When we set NHibernate's show_sql configuration property to true, NHibernate will write all SQL statements to Console.Out. This is handy in some cases, but many applications don't use console output. With a properly configured logger, we can write the SQL statements to the trace output instead.

NHibernate also writes every SQL statement to a logger named NHibernate.SQL. These log messages have DEBUG priority. When we add the following snippet to our configuration, we can redefine the log level for this specific logger. We will get every SQL statement in the trace output, as follows:

<logger name="NHibernate.SQL">
   <level name="DEBUG" />
</logger>

Using other log providers

NHibernate also provides the IInternalLogger interface which facilitates logger abstraction. If you want to use other log providers you can provide an implementation for your favorite logger. There is also an NHibernate.Logging project which provides implementation for the Common.Logging logging abstraction framework. Common.Logging supports log4net, NLog, and Enterprise Library logging frameworks, so you can use any of them with NHibernate via this abstraction. Download NHibernate.Logging from https://github.com/mgernand/NHibernate.Logging or install it from NuGet.

To enable the log provider you have to add the following lines to your App.config or Web.config:

<appSettings>
  <add key="nhibernate-logger" 
       value = 
"NHibernate.Logging.CommonLogging.CommonLoggingLoggerFactory, NHibernate.Logging.CommonLogging"/>
</appSettings>

See also

  • Configuring NHibernate with App.config or Web.config
  • Using NHibernate Profiler

Generating the database

In this recipe, we'll show you how to generate all the necessary tables, columns, keys and relationships in your database - with two lines of code.

Getting ready

Complete the Configuring NHibernate with App.config recipe at the beginning of this chapter.

Note

This recipe works for any RDBMS supported by NHibernate. To use a different system, switch to the dialect for your RDBMS, and use a connection string appropriate for your system.

How to do it...

  1. Open Program.cs.
  2. Add these using statements to the beginning of the file:
    using Eg.Core;
    using NHibernate.Mapping.ByCode; 
    using NHibernate.Tool.hbm2ddl;
  3. Modify the Main method to look like this:
    var nhConfig = new Configuration().Configure();
    var mapper=new ConventionModelMapper();
    nhConfig.AddMapping(mapper.CompileMappingFor(new[] {typeof (TestClass)}));
    
    var schemaExport = new SchemaExport(nhConfig);
    schemaExport.Create(false, true);
    
    Console.WriteLine("The tables have been created"));
    Console.ReadKey();
  4. Build and run your application.
  5. Open your database and examine the tables. If everything worked, a table representing TestClass should have been created.

How it works...

The hbm2ddl (hibernate mapping to data definition language) tool uses the mapping metadata in the configuration object to build a SQL script of our database objects. It then connects to our database and runs this script. In order to demonstrate the functionality, we added a mapping for TestClass. How mappings are created and used will be further discussed in Chapter 2, Models and Mapping.

There's more...

Alternatively, we can use the hbm2ddl.auto configuration property to build our database schema automatically whenever our application calls BuildSessionFactory. We can set the property to the following values:

  • update: The SchemaUpdate class updates our database schema, avoiding destructive changes. This only works for dialects that implement the IDataBaseSchema interface, such as the SQL Server, Oracle, MySQL, PostgreSQL, SQLite, and Firebird dialects.
  • create: The SchemaExport class creates our database schema from scratch for a fresh database.
  • create-drop: SchemaExport recreates the database schema by first dropping and then creating each table.
  • validate: The SchemaValidate class compares the existing database schema to the schema NHibernate expects, based on your mappings. Similar to update, this requires a dialect that implements IDataBaseSchema.

While create-drop is immensely helpful during development, only validate is suggested for production environments, as the tiniest mistake can have huge consequences. Rather, you should script the database, as shown in the next recipe, and run the script explicitly to set up your production database.

See also

  • Configuring NHibernate with App.config or Web.config
  • Scripting the database

Scripting the database

It's usually not appropriate for your application to recreate database tables each time it runs. In this recipe, we'll generate a SQL script to create your database objects.

Getting ready

Complete the Configuring NHibernate with App.config or Web.config recipe at the beginning of this chapter.

Note

This recipe works for any RDBMS supported by NHibernate. To use a different system, adjust your connection string and dialect accordingly.

How to do it...

  1. Open Program.cs.
  2. Add these using statements to the beginning of the file:
    using Eg.Core;
    using NHibernate.Mapping.ByCode; 
    using NHibernate.Tool.hbm2ddl;
  3. Modify the Main method to look similar to this:
    var nhConfig = new Configuration().Configure();
    var mapper = new ConventionModelMapper();
    nhConfig.AddMapping(mapper.CompileMappingFor(new[] { typeof(TestClass) }));
    
    var schemaExport = new SchemaExport(nhConfig);
    schemaExport
        .SetOutputFile(@"db.sql")
        .Execute(false, false, false);
    
    Console.WriteLine("An sql file has been generated at {0}",
                      Path.GetFullPath("db.sql"));
    Console.ReadKey();
  4. Build and run your application.
  5. Inspect the newly created db.sql file.

How it works...

Using the mapping metadata from the configuration object and the current dialect, hbm2ddl builds a SQL script for your entities.

See also

  • Configuring NHibernate with App.config
  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate
  • Generating the database
  • Updating the database

Updating the database

It's usually required to update your database if mappings for your application have changed. In this recipe, we'll generate a SQL script to update your database objects.

Getting ready

Complete the Configuring NHibernate with App.config or Web.config recipe at the beginning of this chapter.

Note

This recipe works for any RDBMS supported by NHibernate. To use a different system, adjust your connection string and dialect accordingly.

How to do it...

  1. Open Program.cs.
  2. Add these using statements to the beginning of the file:
    using Eg.Core;
    using NHibernate.Mapping.ByCode; 
    using NHibernate.Tool.hbm2ddl;
  3. Modify the Main method to look similar to this:
    var nhConfig = new Configuration().Configure();
    var mapper = new ConventionModelMapper();
    nhConfig.AddMapping(mapper.CompileMappingFor(new[] { typeof(TestClass) }));
    var update = new SchemaUpdate(nhConfig);
    update.Execute(false, true);
    Console.WriteLine("The tables have been updated");
    Console.ReadKey();
  4. Build and run your application. Inspect the table(s) in the database.
  5. Modify TestClass to include an additional property:
    public virtual string Description { get; set; }
  6. Build and run the application again. The TestClass table should now have a new column corresponding to the Description property.

How it works...

Using the mapping metadata from the configuration object and the current dialect, hbm2ddl analyzes the existing structure of your database and generates a script to fulfill the differences. The SchemaUpdate only adds missing objects, and does not try to remove anything.

See also

  • Configuring NHibernate with App.config
  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate
  • Generating the database
  • Scripting the database

Using NHibernate schema tool

In many cases, you'll want to include building or updating your database in some larger process, such as a build script or installation process. In this recipe, we'll show you how to use this command-line tool to run our hbm2ddl tasks.

Getting ready

Download the latest release of NHibernate Schema Tool from http://nst.codeplex.com/.

To install NHibernate Schema Tool, follow these steps:

  1. Create a new folder in C:\Program Files named NHibernateSchemaTool.
  2. Copy nst.exe to the newly created folder.
  3. Add C:\Program Files\NHibernateSchemaTool to your PATH environment variable.
  4. Complete the Configuring NHibernate with hibernate.cfg.xml recipe from the beginning of this chapter.

Note

This recipe works for any RDBMS supported by NHibernate. To use a different system, adjust your connection string and dialect accordingly.

How to do it...

  1. Build your solution.
  2. Open a command prompt window, and switch to the directory containing your compiled mapping assembly and hibernate.cfg.xml.

    Note

    To open the command prompt window quickly, in Visual Studio, right-click on your project, and choose Open Folder in Windows Explorer. Open the bin folder. While holding down Shift, right-click on the Debug folder. Choose Open Command Window Here.

  3. Run the following command:
    nst /c:hibernate.cfg.xml /a:Eg
    .Core.dll /o:Create.
    

We haven't added any HBM mapping files to the Eg.Core project yet, so no tables will be created. In the next chapter, however, we will go into some depth on how these mappings are created.

How it works...

NHibernate Schema Tool is a command-line wrapper for the hbm2ddl tool. This makes NST ideal for use in build scripts and continuous integration servers.

The /c argument specifies the configuration file. The /a argument specifies the assembly with our classes and mapping embedded resource files. The /o:Create option tells NHibernate to create our database objects. It also supports Update and Delete.

There's more...

NST has several options, enabling a number of creative uses. NST supports these command-line options:

Command-line option

Description

/c:<path-to-hibernate-config>

Specifies NHibernate config file to use.

/a:<assembly[;assembly2]>

Path to assembly or semicolon-separated list of assemblies containing embedded .hbm.xml files. These assemblies may also contain persistent classes.

/m:<assembly[;assembly2]>

Path to assembly or semicolon-separated list of assemblies containing persistent classes.

/d:<path[;path2]>

Directory or directories containing .hbm.xml mapping files.

/s

Generate script, but don't execute. Script is written to the console.

/v

Generate script and execute. Script is written to the console.

/o:<Create|Update|Delete>

Specifies the Create, Update, or Delete operation.

See also

  • Configuring NHibernate with App.confiig or Web.config
  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate
  • Generating the database
  • Scripting the database
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Master the full range of NHibernate features through detailed example recipes that you can quickly apply to your own applications
  • Reduce hours of application development time and get a better application architecture and improved performance
  • Create, maintain, and update your database structure automatically with the help of NHibernate

Description

NHibernate is a mature, flexible, scalable, and feature-complete open source project for data access. Although it sounds like an easy task to build and maintain database applications, it can be challenging to get beyond the basics and develop applications that meet your needs perfectly. NHibernate allows you to use plain SQL and stored procedures less and keep focus on your application logic instead. Learning the best practices for a NHibernate-based application will help you avoid problems and ensure that your project is a success. The book will take you from the absolute basics of NHibernate through to its most advanced features, showing you how to take full advantage of each concept to quickly create amazing database applications. You will learn several techniques for each of the four core NHibernate tasks—configuration, mapping, session and 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 by the end of the book. You will also 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 features, you will learn creative ways to extend the NHibernate core, as well as gaining techniques to work with the NHibernate search, shards, spatial, envers, and validation projects.

Who is this book for?

This book is written for .NET developers who want to use NHibernate and those who want to deepen their knowledge of the platform. Examples are written in C# and XML. Some basic knowledge of SQL is assumed. If you build .NET applications that use relational databases, this book is for you.

What you will learn

  • Create a persistent object model to move data in and out of your database
  • Build the database from your model automatically
  • Configure NHibernate for use with WebForms, MVC, WPF, and WinForms applications
  • Create database queries using a variety of methods
  • Improve the performance of your applications using a variety of techniques
  • Build an infrastructure for fast, easy, test-driven development of your data access layer
  • Implement entity validation, auditing, full-text search, horizontal partitioning (sharding), and spatial queries using NHibernate Contrib projects

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 31, 2017
Length: 448 pages
Edition : 2nd
Language : English
ISBN-13 : 9781784396428
Category :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 31, 2017
Length: 448 pages
Edition : 2nd
Language : English
ISBN-13 : 9781784396428
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 226.97
NHibernate 4.x Cookbook
NZ$80.99
Learning NHibernate 4
NZ$80.99
.NET Design Patterns
NZ$64.99
Total NZ$ 226.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. The Configuration and Schema Chevron down icon Chevron up icon
2. Models and Mappings Chevron down icon Chevron up icon
3. Sessions and Transactions Chevron down icon Chevron up icon
4. Queries Chevron down icon Chevron up icon
5. Improving Performance Chevron down icon Chevron up icon
6. Testing Chevron down icon Chevron up icon
7. Data Access Layer Chevron down icon Chevron up icon
8. Extending NHibernate Chevron down icon Chevron up icon
9. NHibernate Contribution Projects Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
codemuncher Jan 02, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If your looking to learn about nhibernate this a great book and it gives most examples in both XML and c# code. It covers a variety of basic and advanced subjects and I fully recommend it
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.