Thursday, October 13, 2005

NHibernate 1.0 and Firebird

I've some experiences with Hibernate 2.1 but never touch NHibernate.
It's first time I play around NHibernate, just because I want to test it.
I found that NHibernate meets my all criterias (create DDL, gen mapping on the fly, etc.) to enable MDA.
I use mapping attributes from NHibernateContrib to model a domain class (see below).


// new configuration
Configuration config = new Configuration();
// set properties
IDictionary props = new Hashtable();
props["hibernate.connection.provider"] =
"NHibernate.Connection.DriverConnectionProvider";
props["hibernate.dialect" ] =
"NHibernate.Dialect.FirebirdDialect";
props["hibernate.connection.driver_class"] =
"NHibernate.Driver.FirebirdDriver" ;
props["hibernate.connection.connection_string"] =
"User=SYSDBA;Password=masterkey;" +
"Database=C:\\workspace\\FirebirdNET\\test.fdb;" +
"DataSource=;Port=3050;Dialect=3;Charset=NONE;Role=;" +
"Connection lifetime=0;Connection timeout=15;" +
"Pooling=True;Packet Size=8192;Server Type=0";
config.AddProperties(props);

// auto-generate Hbm on-the-fly
using( MemoryStream stream = new MemoryStream() ) {
HbmSerializer.Default.Serialize(stream, typeof(TestClass));
stream.Position = 0;
config.AddInputStream(stream);
}

// create database schema
SchemaExport s = new SchemaExport(config);
s.Create(true, true);

sf = config.BuildSessionFactory();

// create an object, then save
using(ISession ss = sf.OpenSession()) {
ITransaction tx = ss.BeginTransaction();
TestClass tc = new TestClass();
tc.Id = 1;
ss.Save(tc);
tx.Commit();
ss.Close();
}

// try find the object as IList
using(ISession ss = sf.OpenSession()) {
IList a = ss.Find("from TestClass");
Text = a.Count.ToString();
ss.Close();
}



A sample domain class:


using System;
using NHibernate.Mapping.Attributes;

namespace TestNHibernate {

[Serializable]
[Class(NameType=typeof(TestClass))]
public class TestClass {

public TestClass() {
}

private int id;

[Id(-2, Name="Id")]
[Generator(-1, Class="assigned")]
public int Id {
get{ return id;}
set{ id = value; }
}

}
}

1 comment:

Anonymous said...

Cool!

ไม่เขียนเป็นภาษาไทยบ้างเหรอครับ ดูเหมือน NHibernate จะไม่มีคนเล่นมากนัก (.NET Programmer)