Search code examples
grailsgrails-ormauto-incrementdatabase-sequence

Grails : id generator using assigned and falling back to sequence if unassigned


I am working with Grails 3.2.8. I would like to allow both options when generating an id. Is there a way to use assigned and falling back to sequence if unassigned? I tried getting the next id within a constructor and setting id there but running into issues. Any help/guidance would be most appreciated.

class Foo {
  static mapping = {
    id generator:'assigned'
  }
}

vs

class Foo {
  static mapping = {
    id generator:'sequence'
  }
}

Ive tried using mapping set to assigned and setting the id within the domain constructor of beforeValidate function. Neither are working for me. Examples below.

class Foo{
    Foo(){          
        def id = Foo.find("from Foo order by id desc")
        id = id ? id : 0
        this.id = id
    }
    static mapping = {
        id generator:'assigned'
    }
}

class Foo{
    def beforeValidate() {
        def id = Foo.find("from Foo order by id desc")
        id = id ? id : 0
        this.id = id
    }
    static mapping = {
        id generator:'assigned'
    }
 }

Thanks in advance for your help.


Solution

  • Is there a way to use assigned and falling back to sequence if unassigned?

    No, not directly anyway. You could use assigned and when you wanted to fall back on the sequence you could send a query to the database to retrieve the next sequence value and then assign it yourself. I think that is probably as close as you can probably get.