Mike Croteau
Mike Croteau

Reputation: 1132

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.

Upvotes: 0

Views: 1669

Answers (2)

Adeel Ansari
Adeel Ansari

Reputation: 39907

First of all, you need to understand HQL; in your examples you are returning Foo not id, so it's clearly wrong.

Second, you shouldn't depend on the table for next value of id, because it's not guaranteed to be correct -- you might face id is not unique kinda errors.

Third, you aren't incrementing the id, this way you will end up getting the same, most likely 0, every time.

Here is what you can do, use database sequence -- depends on the database.

"select id_seq.nextval from dual" // for Oracle

Finally, it's a very bad idea -- unless you are having a very good reason for it.

Upvotes: 1

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

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.

Upvotes: 1

Related Questions