Book Image

NHibernate 4.x Cookbook - Second Edition

By : Gunnar Liljas, Alexander Zaytsev, Jason Dentler
Book Image

NHibernate 4.x Cookbook - Second Edition

By: Gunnar Liljas, Alexander Zaytsev, Jason Dentler

Overview of 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.
Table of Contents (17 chapters)
NHibernate 4.x Cookbook Second Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Index

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