Native ID generation with NHibernate

10 commentsWritten on July 17th, 2007 by
Categories: NHibernate, Software Development

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)

  • http://www.mmsoft.ro Marius

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

  • Michael

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

  • Carlos

    Thanks!

  • Dan

    Like all above have said – thanks man!

  • Svein

    Same as all others – great!

    Thanks!

  • David

    PERFECT … exactly what I was looking for! Thanks!

  • Waqas

    thanks, i was looking for the same thing

  • Vgvijay

    hello, I have set

    when I try to insert it comes up with below error, IDENTITY_INSERT is set to OFF.

    this field is set to auto increment in the database?????

    any ideas

  • Pingback: Modificar la configuración de NHibernate por código | Koalite's blog

  • AWSOMEDEVSIGNER

    Wonderful! Thank you for this useful post!