Chapter 4. NHibernate Warm-up

After mappings, configuration is another important concept we should learn before we start using NHibernate for storing/retrieving data from database. In this chapter, we would unfold the knowledge of NHibernate configuration.

We will begin with NHibernate configuration that we had briefly looked at in Chapter 2, Let's Build a Simple Application, when we wrote our first unit test. I had asked you to ignore that piece of code then. Well, we will look in detail now what exactly that code did for us. After this elaboration has enlightened us of NHibernate configuration, we will look at different ways in which NHibernate can be configured. That will be followed by important and commonly used configuration options that we, as a developer, should be aware of. Towards the end of the chapter, we will look at a feature offered by NHibernate that is capable of generating database creation/update scripts by inspecting the mappings declared.

There are no unit tests that we would write for the code in this chapter. This is partly because we were using a bit of configuration already in Chapter 2, Let's Build a Simple Application, which is tested through the unit tests we wrote there. Besides that, NHibernate configuration is not our application logic and hence there is no point in writing and maintaining unit tests for it.

Warming up NHibernate succinctly

Following is a piece of code from the previous chapter that I had asked you to ignore then:

using System;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Tool.hbm2ddl;
using Environment = NHibernate.Cfg.Environment;

namespace Tests.Unit
{
  public class InMemoryDatabaseForXmlMappings : IDisposable
  {
    protected Configuration config;
    protected ISessionFactory sessionFactory;
    public ISession Session;
    public InMemoryDatabaseForXmlMappings()
    {
      config = new Configuration()
      .SetProperty(Environment.ReleaseConnections, "on_close")
      .SetProperty(Environment.Dialect, typeof
      (SQLiteDialect).AssemblyQualifiedName)
      .SetProperty(Environment.ConnectionDriver, typeof
      (SQLite20Driver).AssemblyQualifiedName)
      .SetProperty(Environment.ConnectionString, "data
      source=:memory:")
      .AddFile("Mappings/Xml/Employee.hbm.xml");

      sessionFactory = config.BuildSessionFactory();

      Session = sessionFactory.OpenSession();

      new SchemaExport(config).Execute(
      useStdOut:true,
      execute:true,
      justDrop:false,
      connection:session.Connection,
      exportOutput:Console.Out);
    }


    public void Dispose()
    {
      Session.Dispose();
      sessionFactory.Dispose();

    }
  }
}

I had told you that the preceding code is giving us an in-memory database that we could use to run unit tests. We will dissect this code now. This code collectively summarizes what we are going to learn in this chapter. Ignoring the usual class declaration and implementation of IDisposable, let's jump straight into the constructor of the preceding class:

config = new Configuration()

The preceding line creates an instance of the Configuration class. All NHibernate settings are configured via this class.

.SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)

Here you call the SetProperty method on configuration object to set various properties of your configuration. In this particular line, we are setting a property called Dialect. Dialect tells NHibernate what database technology the underlying database belongs to; for example, MS SQL Server 2008 R2, Oracle 10g, and so on. In a later section of this chapter, we will look at Dialect in detail along with other important properties that can be set via configuration object. Other properties that are set in the previous example are database driver, connection string, and connection release mode. Database driver, as the name suggests, tells NHibernate which database driver library it should use to communicate with the database. Connection string is well known – it is address of the database. Connection release mode defines when the acquired ADO.NET connection should be released. We have declared it to be on_close which means release the connection after the session is closed. Again, all these properties are discussed in detail later in this chapter. Let's move on to the next line of code:

.AddFile("Mappings/Xml/Employee.hbm.xml");

This preceding line tells the configuration object that it should use mappings declared in Employee.hbm.xml. Again, there are several ways we can tell configuration to use different mappings. Here, we are seeing one that is most simple. We will soon learn other ways. At this point, minimal configuration required to interact with database is complete. In order to start interacting with database, we first need to build a session factory. Next line of code does exactly that:

sessionFactory = config.BuildSessionFactory();

sessionFactory lets us create an instance of the ISession object by invoking the OpenSession method as we can see in the next line of code:

Session = sessionFactory.OpenSession();

Session is one object that you would be using most widely while working with NH. This object seamlessly manages database interaction while you keep saving/retrieving entities using various methods offered by it. In the next line of code, we use the configuration object and session object to build an instance of a special class named SchemaExport:

new SchemaExport(config).Execute(
  useStdOut:true,
  execute:true,
  justDrop:false,
  connection:session.Connection,
  exportOutput:Console.Out);

The SchemaExport class uses mappings and settings from configuration to generate database creation scripts in accordance with the declared mappings. It can optionally run these scripts against the database specified in configuration via connection string. We will look at this aspect in detail towards the end of this chapter.

This brings us to the end of succinctly warming up NH. Rest of the chapter elaborates in more detail what we just covered briefly. Besides examining configuration options available to developers, we will also learn about different ways of configuring NH. We will start with a dive into session architecture of NHibernate next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset