1

I am struggling to insert JPA mapped entities (via a Spring Data CrudRepository) into a table on SQL Server 2019 that has a primary key column of type UNIQUEIDENTIFIER and a default value of NEWID().

CREATE TABLE some_table
(
  id UNIQUEIDENTIFIER not null primary key default NEWID(),
  -- ...
)

The problem is that all variations I managed to get to work involve a UUID generator on the JPA/Hibernate side and I end up with two different UUID values in the table and the saved JPA entity object.

E.g. this mapping "works" in the sense that there is no error reported, but the saved entity object's id field contains a different UUID than what is saved as a PK value in the underlying table.

@Entity
@Table(name = "some_table")
public class MyEntity {

    @Id
    @Column(columnDefinition = "uniqueidentifier")
    @GeneratedValue
    private UUID id;

    // ...
}

// id field not set
myEntityRepository.save(myEntity);
// if field set, but value differs from DB

Using @GeneratedValue (strategy = GenerationType.IDENTITY) yields a

org.hibernate.id.IdentifierGenerationException: unrecognized id type : uuid-binary -> java.util.UUID

despite the columndefinition.

How do I have to set up the mapping to either correctly pick up the UUID value generated by SQL Server or store the UUID value generated by a Hibernate generator strategy?

Ralf
  • 6,735
  • 3
  • 16
  • 32
  • 1
    Is this [relevant](https://stackoverflow.com/a/42485612/390122)? – AlwaysLearning Oct 05 '21 at 21:19
  • The `@Type` annotation did the trick. I never noticed that the UUIDs were actually the same but had different representation. Thanks for googling that for me! – Ralf Oct 06 '21 at 07:12

1 Answers1

0

With Spring 3 / Hibernate 6 @Type(type = "uuid-char") is not available anymore.

You can specify

spring.jpa.properties.hibernate.type.preferred_uuid_jdbc_type: CHAR

in your application.yml in order to convert uuid type globally.

See also: https://docs.jboss.org/hibernate/orm/6.2/migration-guide/migration-guide.html