The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

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)

6 Responses to “Native ID generation with NHibernate”

  1. Marius Says:

    This is exactly what I was looking for, thank you!

  2. Michael Says:

    Thanks for this! I’ve read 20 other explanations of how this works, but couldn’t find any details. This really helps!

  3. Carlos Says:

    Thanks!

  4. Dan Says:

    Like all above have said – thanks man!

  5. Svein Says:

    Same as all others – great!

    Thanks!

  6. David Says:

    PERFECT … exactly what I was looking for! Thanks!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>