Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an uuid or guid as id in grails/hibernate

I need to have GUID/UUID's as the id column of my rows.

This is to be able to create entries both online and offline, and of course not having these conflict on PK when merging. I know i could mitigate this, but i'd like to keep it simple, and there is legacy apps already using uuid/guids to define relationships). Data also needs to be synced both ways later. Rewriting existing applications is not an option.

When i try to use either GUID or UUID with grails i get an error 500. (using a GUID on h2 results in another error - detaling that DB does not support GUIDs, as expected).

I get this error when i try to save an 'WithUUID':

URI    /gtestUUID/withUUID/save
Class    java.lang.IllegalArgumentException
Message    argument type mismatch

Entire Error 500: http://imgur.com/m2Udbm6.png

I've tried with mariadb 5.5 and 1.1.7 driver, this results in the same problem.

Grails 2.3.8. Windows 8.1 (x64). Netbeans 7.4

all default.

Example classes:

WithUUID.groovy:

package gtestuuid

class WithUUID {
    String name
    static constraints = {
    }
    static mapping = {
        id generator: 'uuid'
    }
}

WithUUIDController.groovy:

package gtestuuid

class WithUUIDController {
    def scaffold = WithUUID
}

Any help would be greatly appreciated.

Link to relevant grails documentation

(i'm not able to post links to more docs/posts due to my low rep)

like image 532
user3218163 Avatar asked May 19 '14 11:05

user3218163


2 Answers

Or you can specify UUID id field in your class without any initializing and set mapping like in this case

class Buyer {

    UUID id
    String name
    String phone
    String email

    static constraints = {
    }

    static mapping = {
        id generator : 'uuid2', type: 'pg-uuid' // pg-uuid because I use postgresql
    }

}

You can take out mapping in Config.groovy

grails.gorm.default.mapping = {
    id generator : 'uuid2', type: 'pg-uuid'
}

and your classes will contain only UUID id field without any redudant code

like image 177
dimedrol90 Avatar answered Oct 16 '22 17:10

dimedrol90


You need to set the id as String or UUID (or anything you need).

Below, an example of my class User with another possibility:

import java.util.UUID

class User {

    String id = UUID.randomUUID().toString()

    static mapping = {
        id generator:'assigned'
    }
}
like image 38
Abincepto Avatar answered Oct 16 '22 17:10

Abincepto