grailsgrails-2.4

Manually update autogenerated id by GORM


I'm working with class:

 class Account{
      static mapping = {
          id generator: "uuid2"
      }
 }

I try to add instance of account and manually set its id:

new Account(id: accountId).save(flush:true)

but after flush, id of saved object is changing. I'd like to leave default engine of autogenerating id, but I want also to add functionality to add object with specified id. How can I obtain it? Grails 2.4.5 here.

And an error from stacktrace:

Message: identifier of an instance of com.example.Account was altered from x... to y...


Solution

  • I'd modified @Sandeep Poonia (+1) answer and finally found satisfying solution:

      import java.util.UUID
    
      class Account{
            UUID id
    
            static mapping = {
                id generator: "assigned"
            }
    
            def beforeInsert() {
                  if(!id){
                        id = UUID.randomUUID().toString()
                  }
            }
      }