Native ID generation with NHibernate
Posted by Davy Brion on July 17th, 2007
i was looking for a way to define the mapping of an ID field so it would work on both Oracle and SQL Server… In case of Oracle, it would have to use a Sequence that i can define. On Sql Server, it should use an Identity column. Luckily, NHibernate offers just that… the ‘native’ ID generator uses identity on sql server and a sequence on Oracle.
Unfortunately the ‘native’ generator is hardly documented in the Nhibernate reference documentation so it wasn’t really clear to me which sequence would be used, or how i could define my own. All the documentation says is basically:
For cross-platform development, the native strategy will choose from the identity, sequence and hilo strategies, dependent upon the capabilities of the underlying database.
So how can you define which sequence it should use in case of Oracle? Very simple actually… turns out you just define the sequence name in the same way you would as if you set it to use the ‘sequence’ generator.
So here’s how you do it:
<id name="Id" column="CustomerId" type="long" unsaved-value="-1"
access="field.camelcase-underscore">
<generator class="native" >
<param name="sequence">sq_customer</param>
</generator>
</id>
On Oracle, it will use the sq_customer sequence whereas on SQL Server the sequence parameter will be ignored and it will use the Identity setting of the column that was defined as the ID (in this case, CustomerId’s Identity settings)

August 30th, 2007 at 10:59 pm
This is exactly what I was looking for, thank you!
February 20th, 2008 at 11:52 pm
Thanks for this! I’ve read 20 other explanations of how this works, but couldn’t find any details. This really helps!
November 1st, 2008 at 3:11 pm
Thanks!
May 5th, 2009 at 5:29 pm
Like all above have said – thanks man!
May 19th, 2009 at 11:51 am
Same as all others – great!
Thanks!
September 8th, 2009 at 10:35 pm
PERFECT … exactly what I was looking for! Thanks!