سؤال

Instead of a sequence of ID which GORM creates, I want to use a 16 digit random number as ID for all the tables GORM creates. I need help as to how to do that. I tried doing

static mapping = { id generator: 'uuid2' }

it didnt work. Help appreciated

هل كانت مفيدة؟

المحلول

You can use a simple mapping like:

class Book {
    static mapping = {
        id generator:'assigned'
     }
    def beforeInsert() {
        id = YourRandomGenerator.nextInt()
    }
}

Note the use of the beforeInsert event to assign the id. Greetings.

نصائح أخرى

If all you want to do is do a custom generator, you can extend IdentifierGenerator:

class CustomGenerator extends IdentifierGenerator {
    Serializable generate(SessionImplementor session, Object object) {
        return "myroutine"
    }
}

class Book {
    String id
    static mapping = {
         generator:"some.package.CustomGenerator", column:"id", unique:"true"
    }
}

You can create a custom id generator as shown below

public class CustomIdGenerator implements IdentifierGenerator {

public synchronized Serializable generate(final SessionImplementor session, Object obj) {
        return GENERATED ID; //return generated id 
    }
}

Now, if you want it to use for some specific domains only.. Then you can do it in mappings closure like this

mapping = {
        id generator:'packagename.CustomIdGenerator'
    }

But if you want all your domains to use the custom id generator, you can specify it in Config.groovy like this, and it will apply to all the domains

grails {
  gorm.default.mapping = {
        id column: 'id', generator:'packagename.CustomIdGenerator'
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top