0

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...

Michal_Szulc
  • 4,097
  • 6
  • 32
  • 59

2 Answers2

2

You can not modify the identifier once it has been set for an object. Doing so will throw an exception like the one you are getting. So if you want to use a UUId value as you id but want to assign it manually then instead of using "uuid2" generation strategy, you would have to use "assigned" strategy. Correct way would be:

class Account{
      UUID id

      static mapping = {
          id generator: "assigned"
      }
 }
Sandeep Poonia
  • 2,158
  • 3
  • 16
  • 29
0

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()
              }
        }
  }
Michal_Szulc
  • 4,097
  • 6
  • 32
  • 59