Proper Hibernate id generator for postgres serial/bigserial column?

Matt Huggins picture Matt Huggins · Aug 8, 2010 · Viewed 19.5k times · Source

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>

Answer

Pascal Thivent picture Pascal Thivent · Aug 8, 2010

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.