NHibernate 4.x Cookbook - Second Edition

5 (1 reviews total)
By Gunnar Liljas , Alexander Zaytsev , Jason Dentler
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. The Configuration and Schema

About this book

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.

Publication date:
January 2017
Publisher
Packt
Pages
448
ISBN
9781784396428

 

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:

  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:

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

About the Authors

  • Gunnar Liljas

    Gunnar Liljas is a software architect with more than 20 years' experience in developing and designing web-based solutions. His focus has been on data-driven content publishing, not only for the Web, but also for automated and on-demand print publishing. Currently, he spends most of his waking hours at the Swedish CRM supplier Revide, where he uses tools such as NHibernate and Redis to create targeted emails, text messages, and campaign web sites based on massive data sources.

    He's also one of the lead contributors to the NHibernate open source project.

    In his spare time, Gunnar sings in two classical choirs and often performs with the renowned Norrköping Symphony Orchestra.

    Browse publications by this author
  • Alexander Zaytsev

    Alexander Zaytsev discovered his passion for IT when he was a small kid, and since then he has dedicated his life to becoming an excellent software developer. Alexander has many years' experience in the IT field, analyzing, designing, and developing .NET-based enterprise applications, using cutting-edge technologies. He works as an independent consultant in the .NET space, providing technical expertise to all kinds of software development companies. He is an active member of open source and local development communities, and writes a blog at http://alexzaytsev.me. He is one of the main contributors to the NHibernate project, and one of the few people who really know the NHibernate internals.

    He is adept in Agile software development, and he believes that Agile practices such as test-driven development, pair programming, automated testing, continuous integration, and deployment are the keys to quality software.

    He lives in Auckland with his wife, Olga, and son, Stepan. In his spare time, he loves spending time with his family, cycling, and doing coding just for fun.

    Browse publications by this author
  • Jason Dentler

    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's worked in a few different industries. Currently, he builds really awesome software in higher education. He's an Eagle Scout and a graduate of the University of Houston – Victoria.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Le contenu c'est bon et objectif.

Recommended For You

C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development - Fourth Edition

Learn the fundamentals, practical applications, and latest features of C# 8.0 and .NET Core 3.0 from expert teacher Mark J. Price.

By Mark J. Price
Hands-On Domain-Driven Design with .NET Core

Solve complex business problems by understanding users better, finding the right problem to solve, and building lean event-driven systems to give your customers what they really want

By Alexey Zimarev
Hands-On Software Architecture with C# 8 and .NET Core 3

Design scalable and high-performance enterprise applications using the latest features of C# 8 and .NET Core 3

By Francesco Abbruzzese and 1 more