Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Hibernate id generator for postgres serial/bigserial column?

My PostgreSQL tables have id's of type bigserial, meaning they are generated at the time rows are inserted (and thus, the id column's value is not supplied in the INSERT statement). I'm having difficulty finding the proper value for the <generator class="..."> attribute in my XML mapping file.

The code below is the closest I've found that seems to be the closest for Postgres, but it's still performing a SELECT nextval(...) on the sequence before inserting (and explicitly including the id field's value on the insert). I just want Hibernate to not include the id field value at all, allowing Postgres to do its job of generating the value itself.

    <id name="id" column="id" type="java.lang.Long">
        <generator class="sequence">
            <param name="sequence">my_sequence_name</param>
        </generator>
    </id>
like image 285
Matt Huggins Avatar asked Aug 08 '10 09:08

Matt Huggins


2 Answers

This is undocumented but you can actually use an identity generator with PostgreSQL when the PK is of type SERIAL or BIGSERIAL:

<id name="id" column="user_id" type="java.lang.Long">
     <generator class="identity"/>
</id>

See HB-875 and HHH-1675 for background on this.

like image 187
Pascal Thivent Avatar answered Oct 28 '22 11:10

Pascal Thivent


From what i read:

<id name="id" column="id" type="java.lang.Long">
    <generator class="sequence">
        <param name="sequence">my_sequence_name</param>
    </generator>
</id>

should work faster than:

<id name="id" column="id" type="java.lang.Long">
    <generator class="identity" />
</id>

The sequence generator falls in the Non-insert POID generators described like this:

Non-insert POID generators are the best option for new applications. These generators allow NHibernate to assign an identity to a persistent object without writing the object's data to thedatabase, allowing NHibernate to delay writing until the business transaction is complete, reducing round trips to the database.

While the identity generator is Post-insert POID generators group:

Post-insert POID generators require data to be persisted to the database for an ID to be generated. This alters the behavior of NHibernate in very subtle ways and disables some performance features. As such, use of these POID generators is strongly discouraged! They should only be used with existing databases where other applications rely on this behavior.

Quotes were taken from NHibernate 3.0 Cookbook.

like image 33
Răzvan Flavius Panda Avatar answered Oct 28 '22 12:10

Răzvan Flavius Panda