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?