Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different representation of UUID in Java Hibernate and SQL Server

Tags:

I am trying to map a UUID column in POJO to SQL Server table column using Hibernate.

The annotations are applied as follows:

@Id @GeneratedValue @Column(name = "Id", columnDefinition = "uniqueidentifier")  public UUID getId(){ ... } 

However, it seems that there is some endianness problem between the Java Hibernate mapping and SQL server.

For example, in my Java app, I have ids represented as:

4375CF8E-DEF5-43F6-92F3-074D34A4CE35 ADE3DAF8-A62B-4CE2-9D8C-B4E4A54E3DA1 

whereas in SQL Server, these are represented as:

8ECF7543-F5DE-F643-92F3-074D34A4CE35 F8DAE3AD-2BA6-E24C-9D8C-B4E4A54E3DA1 

Is there any way to have same representation at both sides?

Please note that uniqueidentifier is used only to have a uniqueidentifier typed id in SQL server instead of type binary; the same problem exists when uniqueidentifier is removed from annotation (the problem can be observed by converting binary is to uniqueidentifier).

like image 617
Sayan Pal Avatar asked Jan 14 '17 15:01

Sayan Pal


People also ask

What is UUID in Hibernate?

This annotation defines the Hibernate type mapping. Using “uuid-char” instructs Hibernate to store the UUID as a String, instead of the binary value. This way, it can be written to and read from a VARCHAR(36) column without the need for any pre-processing on our side.

What is the data type of UUID in SQL?

The UUID data type is considered a subtype of the STRING data type, because UUID values are displayed in their canonical textual format and, in general, behave the same as string values in the various SQL operators and expressions.

Is Newid unique in SQL Server?

In assigning the default value of NEWID() , each new and existing row has a unique value for the CustomerID column.


2 Answers

You need to specify the @Type(type = "uuid-char") in addition to @Column(name="...", columnDefinition = "uniqueidentifier"), see also Problems mapping UUID in JPA/hibernate .

Alternatively you can use a String field for the id in Java and still keep uniqueidentifier in SQL Server.

like image 56
Markus Ratzer Avatar answered Oct 03 '22 22:10

Markus Ratzer


Microsoft databases use GUIDs. It is Microsoft's implementation of the UUID standard.

This being said, you should use the guid generator.

@Id @GenericGenerator(name = "generator", strategy = "guid", parameters = {}) @GeneratedValue(generator = "generator") public String getId() {     return id; } 

guid uses a database-generated GUID string on MS SQL Server and MySQL.

Also, have you set SQLServer2012Dialect? This also might solve some future issues.

like image 40
Nico Van Belle Avatar answered Oct 04 '22 00:10

Nico Van Belle