In Chapter 1, we built mappings to map our persistent classes to the database, but we haven't built that database.
In this recipe, I'll show you how to generate all the necessary tables, columns, keys and relationships in your database from your mappings—with two lines of code.
Program.cs
.using
NHibernate.Tool.hbm2ddl;.
Main
.var schemaExport = new SchemaExport(nhConfig); schemaExport.Create(false, true);
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.
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.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. Like 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.