我正在使用 MongoDb 数据库和grails 2.2.2 在这里我想分配一个随机的Id而不是默认的增量Id由Db生成。
例如: abcd.com/demo/view/14524 而不是
的 abcd.com/demo/view/5
我的域代码:
student.groovy
class student{
static mapping = {
id generator:'assigned'
}
static constraints = {
id generator:'assigned'
}
def beforeInsert() {
Random randomNumber = new Random();
id=randomNumber.nextInt(100**4);
println "id "+ id;
}
}
这是依赖列表: -
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// specify dependency exclusions here; for example, uncomment this to disable ehcache:
// excludes 'ehcache'
}
log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
grailsCentral()
mavenLocal()
mavenCentral()
// uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
//mavenRepo "http://snapshots.repository.codehaus.org"
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
}
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
// runtime 'mysql:mysql-connector-java:5.1.20'
compile 'org.imgscalr:imgscalr-lib:4.1'
}
plugins {
runtime ":hibernate:$grailsVersion"
runtime ":jquery:1.8.3"
runtime ":resources:1.1.6"
// Uncomment these (or add new ones) to enable additional resources capabilities
runtime ":zipped-resources:1.0"
runtime ":cached-resources:1.0"
//runtime ":yui-minify-resources:0.1.4"
compile ":cache-headers:1.1.5"
build ":tomcat:$grailsVersion"
runtime ":database-migration:1.2.1"
compile ':cache:1.0.1'
compile ":rest:0.7"
compile ":rendering:0.4.4"
compile ":mail:1.0.1"
compile ":oauth:2.1.0"
compile ":spring-security-core:1.2.7.3"
compile ":spring-security-ui:0.2"
compile ":jquery-ui:1.8.24"
compile ":famfamfam:1.0.1"
compile ":calendar:1.2.1"
}
}
但是给出错误。 是否有其他选项可以分配随机ID?
谢谢。 :)
答案 0 :(得分:1)
您可以将Mongo的ObjectId用作随机标识符:
import org.bson.types.ObjectId
class Student {
ObjectId id
String name
}