Skip to content
Advertisement

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)

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement