Search code examples
postgresqlhibernateliquibase

UUID Generated Values with Hibernate and Postgres


I have a question about UUID generated values.

We are using Hibernate/JPA for our persistence, and Liquibase for DDL.

If we define a table such as:

<changeSet author=".." id="1234-create-books">
  <createTable tableName="books">
    <column name="id" type="UUID" defaultValueComputed="uuid_generate_v1mc()">
      <constraints nullable="false" primaryKey="true" primaryKeyName="pk_books"/>
    </column>
    ...
  </createTable>
</changeSet>

But then define the Entity like:

@Entity
public static class Book {

    @Id
    @GeneratedValue
    private UUID id;
    
    ...
}

Can I confirm that Hibernate would take precedence, and generate a UUID value using:

The default strategy is a version 4 (random) strategy according to IETF RFC 4122.

As opposed to using the v1 strategy defined with default value computed?


Solution

  • Yes, that's how SQL works. A default for a column is only used when you are not mentioning the column in an insert, but Hibernate will always set a value for the id column in inserts. If you want to use uuid_generate_v1mc(), you will have to write a custom IdentifierGenerator. See https://thorben-janssen.com/custom-sequence-based-idgenerator/ for an example.