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
€41.99
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
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Jason Dentler Profile Icon Zaytsev Profile Icon Darshan Joshi Profile Icon Liljas
Arrow right icon
€41.99
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
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Germany

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Germany

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 116.97
NHibernate 4.x Cookbook
€41.99
Learning NHibernate 4
€41.99
.NET Design Patterns
€32.99
Total 116.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela