11

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)
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
George Armhold
  • 30,824
  • 50
  • 153
  • 232

2 Answers2

17

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;
Alan
  • 303
  • 3
  • 10
Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • 1
    I convinced our DBA to move to integer-based PKs, but before doing so I applied your columnDefinition="uniqueidentifier" suggestion, which solved type mismatch issue. – George Armhold May 05 '12 at 19:45
  • Worked for me also. Note that I was able to remove the "parameters" argument from @ GenericGenerator and "name" from @ Column. I didn't want to override those values =) – Stan Kurdziel Apr 22 '13 at 21:17
  • 3
    Warning! [GUIDGenerator](https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/id/GUIDGenerator.html) is DEPRECATED : use [UUIDGenerator](https://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/id/UUIDGenerator.html) instead with custom [UUIDGenerationStrategy](https://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/id/UUIDGenerationStrategy.html) implementation. Nowadays it should be `@GenericGenerator(name = "generator", strategy = "uuid2")`. – naXa stands with Ukraine Oct 24 '17 at 13:07
0

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.

prem30488
  • 2,828
  • 2
  • 25
  • 57
  • Your solution contains the columnDefinition="uniqueidentifier" settings which is mentioned in the accepted answer. Does you solution work without this settings? – HowToTellAChild Mar 09 '23 at 15:27