dboshardy dboshardy - 3 months ago 22
Java Question

Hibernate and Postgresql autoincrement not syncing

I'm having a problem with Hibernate and Postgres. I'm repeating through a code block for testing purposes to make sure everything is working properly. This code block, however, includes repeat persist methods to persist two user accounts to the useraccount table. It works properly the first time. However, every subsequent time I run the code, the UserAccount objects IDs are incremented, while their corresponding users in the table stay at their original values. I've tried using

as the generator class,
keeps the id at
has the same issue I've described above.

I realize this is an unrealistic circumstance (repeating through an identical codeblock) but I don't feel that this is performing as it should. In fact, after removing all entries from all tables, the users are added to the user table properly. Is there a way to ensure that he object property id syncs with the table id?

Here is the xml mapping for the useraccount ids.

<class name="UserAccount" table="useraccounts">
<id name = "UserId" type="int" column="user_id" unsaved-value="null">
<generator class="increment"/>

And here is the Hibernate config file

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
<property name="hibernate.dialect">
<property name="hibernate.connection.driver_class">
<property name="hibernate.connection.url">
<property name="hibernate.connection.username">
<property name="hibernate.connection.password">
<property name="connection_pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="hibernate.hbm.xml"/>



You should use a sequence identifier generator, because Postgres doesn't support IDENTITY columns natively. It supports SERIAL columns which emulate IDENTITY columns by using a sequence behind the scenes. Postgres supports sequences which are much more efficient than IDENTITY anyway.

So your id definition should look like this:

<id name="UserId" column="user_id">
    <generator class="sequence">
        <param name="sequence">USER_ID_SEQUENCE</param>