MSSQL mapping of uniqueidentifier Hibernate 5

Viewed 167

My problem is that I have the following JPA entity:

@Entity
@Table(name = "keys")
class Key(
        @Id
        @Column(name = "key_hash", length = 130, nullable = false)
        var keyHash: String,

        @Column(name = "external_id", nullable = true)
        var externalId: UUID?
)

It works perfectly fine with Postgres, H2 etc. but the UUID mapping seems to be failing on SQL Server. With the following liquibase script:

<changeSet id="keys" author="h311z">
        <createTable tableName="keys">
            <column name="key_hash" type="NVARCHAR(130)">
                <constraints nullable="false"/>
            </column>
            <column name="external_id" type="uuid">
                <constraints nullable="true"/>
            </column>
        </createTable>
</changeSet>

It seems like that Hibernate expects my UUID to be stored as binary(255) however, it is stored as uniqueidentifier. Is there a way to override this?

If I run the liquibase migration first, then run my program I get the following exception:

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: 
Schema-validation: wrong column type encountered in column [external_id] 
in table [keys]; found [uniqueidentifier (Types#CHAR)], 
but expecting [binary(255) (Types#BINARY)]

I have my own dialect for SQL Server which looks like this (using Kotlin but that shouldn't be a problem):

class SQLServerUnicodeDialect : SQLServer2008Dialect() {

    init {
        registerColumnType(Types.CHAR, "nchar(1)");
        registerColumnType(Types.LONGVARCHAR, "nvarchar(max)" );
        registerColumnType(Types.VARCHAR, 4000, "nvarchar(\$l)")
        registerColumnType(Types.VARCHAR, "nvarchar(max)")
        registerColumnType(Types.CLOB, "nvarchar(max)" )

        registerColumnType(Types.NCHAR, "nchar(1)")
        registerColumnType(Types.LONGNVARCHAR, "nvarchar(max)")
        registerColumnType(Types.NVARCHAR, 4000, "nvarchar(\$l)")
        registerColumnType(Types.NVARCHAR, "nvarchar(max)")
        registerColumnType(Types.NCLOB, "nvarchar(max)")

        registerColumnType(Types.VARBINARY, 4000, "varbinary($1)")
        registerColumnType(Types.VARBINARY, "varbinary(max)")
        registerColumnType(Types.BLOB, "varbinary(max)")
    }
}

I tried searching how to solve this but couldn't find anything. Even if I add the GUID type from Microsoft with registerColumnType it doesn't work.

I want to support multiple databases (Postgres, SQLServer etc), so using entities with annotations like columnDefinition is not going to work.

Thanks!

0 Answers
Related