2008年7月2日 星期三

NHibernate Schema Export How To

I am developing a information system to manage mass customization manufacturing. In order to reduce the development time span, .Net 2.0 was chosen to make this happen. Constructing the persistance layer is very important for the system. By using NHibernate, we can take the advantage of OR mapping.
SchemaExport is the class can help us construct the database by using our mapping file(*.hbm.xml).
Once you finish your mapping file, you can use the following code to generate your database schema.

ISessionFactory sessions =null;

NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.Properties.Add("hibernate.dialect", "NHibernate.Dialect.MySQLDialect");
cfg.Properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.MySqlDataDriver");
cfg.AddAssembly("ProjectDAO");
sessions = cfg.BuildSessionFactory();

SchemaExport se = new SchemaExport(cfg);
System.Data.IDbConnection dbconn = new MySql.Data.MySqlClient.MySqlConnection("Server=localhost;Database=agentpjm;User ID=root;Password=h300;");
dbconn.Open();
StringBuilder sb = new StringBuilder();

se.SetOutputFile("c:\\db.txt");
se.SetDelimiter(";\n");
try
{
se.Execute(false, true, false, false, dbconn, new System.IO.StringWriter(sb));
}
catch (Exception ex)
{
MessageBox.show(ex.Message); //show you what's going on
MessageBox.show(sb.ToString()); //show you the DDL generated by the program
}
dbconn.Close();

You have to using the following namespace into your program.
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Tool.hbm2ddl;
using System.Reflection;

Remarks:
Be ware your mapping file. I spent a lot of time to fix my mapping file or you will notice by the exception message. I also listed the DDL information which is generated by SchemaExport. This information really help me to debug my mapping syntax.

Reference

  1. http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/example-parentchild.html

沒有留言: