Thursday, October 13, 2005

Sequence = Firebird Generator in NHibernate 1.0

Code below shows how to use "sequence" to have an auto-incremental field in NHibernate 1.0 with Firebird.
I use Generator(Class="sequence") to make a field to be autoinc, and if you want to specify a generator name, you can use a Param(Name="sequence", Content) attribute.


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

private int _id;
private string _name;

public TestClass() {
}

[Id(1, Name="Id")]
[Generator(2, Class="sequence")]
[Param(3, Name="sequence", Content="TestClass_Id_Gen")]

public int Id {
get{ return _id;}
set{ _id = value; }
}

[Property(Name="Name", Length=10)]
public string Name {
get { return _name; }
set { _name = value; }
}
}
}

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; }
}

}
}