Hibernate and Postgresql autoincrement not syncing

2k Views Asked by At

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 native and identity as the generator class, identity keeps the id at 0 and native 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"/>
    </id>

And here is the Hibernate config file

 <?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE hibernate-configuration SYSTEM
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
 <session-factory>
    <property name="hibernate.dialect">
        org.hibernate.dialect.PostgreSQL82Dialect
    </property>
    <property name="hibernate.connection.driver_class">
        org.postgresql.Driver
    </property>
    <property name="hibernate.connection.url">
       jdbc:postgresql://localhost:5432/agora-db
    </property>
    <property name="hibernate.connection.username">
        postgres
    </property>
    <property name="hibernate.connection.password">
        postgres
    </property>
    <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"/>

 </session-factory>
 </hibernate-configuration>
1

There are 1 best solutions below

1
On BEST ANSWER

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>
    </generator>
</id>