George Armhold
George Armhold

Reputation: 31074

JPA: how to map SQL Server uniqueidentifier type

I've inherited a SQL Server database that I'm trying to map via JPA. Many of the tables have a uniqueidentifier column. I'm trying to map them like so:

@Id
@GenericGenerator(name = "generator", strategy = "guid", parameters = {})
@GeneratedValue(generator = "generator")
@Column(name = "APPLICATION_ID")
private String id;

Hibernate complains with:

Found: uniqueidentifier, expected: varchar(255)

Upvotes: 11

Views: 24682

Answers (2)

prem30488
prem30488

Reputation: 2856

You need to use uuid2

@Id
@GenericGenerator(name = "generator", strategy = "uuid2", parameters = {})
@GeneratedValue(generator = "generator")
@Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
private String id;

This works for me.

Upvotes: 0

Ken Chan
Ken Chan

Reputation: 90507

The data type of the primary key property in the POJO determines the data type of its mapped DB column, which is specified by the Dialect class. According to the SQLServerDialect provided by hibernate, it does not have any data type that maps to uniqueidentifier, and String by default maps to varchar(255)

I think guid strategy on a String primary key only means that hibernate will generate a GUID value for POJO's primary key property and this generated GUID value will be inserted to the varchar(255) column to simulate the effect of uniqueidentifier

You can try to override the mapping specified by the Dialect class by using the columnDefinition attribute of @Column

 @Id
 @GenericGenerator(name = "generator", strategy = "guid", parameters = {})
 @GeneratedValue(generator = "generator")
 @Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
 private String id;

Upvotes: 17

Related Questions