在Grails中将自定义ID生成定义为默认值的最佳方法是什么? [英] What's the best way to define custom id generation as default in Grails?

查看:86
本文介绍了在Grails中将自定义ID生成定义为默认值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想切换我的域类以对其ID使用可变长度的UUID.我不想简单地在URL上显示顺序ID,以供人们尝试使用.我编写了Java UUID方法的自定义版本,以允许可变长度,因此对于不会变大的模型,我可以使用较短的ID.

I want to switch my domain classes to use a variable length UUID for their ids. I don't want to simply display sequential ids on the URL for people to try and mess with. I've written a custom version of the Java UUID method to allow for variable length so I can have shorter ids for models that won't grow large.

我发现此线程说明了如何修改默认映射,以便可以更改为已分配". 修改Grails插件的ID生成

I found this thread that explained how to modify the default mapping so I can change to 'assigned'. Modify Id generation for a Grails Plugin

同时配置默认的beforeInsert(以生成自定义UUID)并告诉Grails我想使用字符串代替id而不是整数的最佳方法是什么?

What's the best way to also configure a default beforeInsert (to generate the custom UUID) and tell Grails I want to use strings for ids instead of integers?

我尝试将 grails.gorm.default.beforeInsert 添加到配置中,但这没用.

I tried adding grails.gorm.default.beforeInsert to the config but that didn't work.

推荐答案

要使grails使用字符串作为id,只需声明属性String id.要使用自定义UUID填充它,我将使用休眠ID生成器,而不是beforeInsert.创建一个扩展org.hibernate.id.IdentifierGenerator的类,然后将这样的id生成器映射添加到您的域类中:

To make grails use strings for the ids, just declare a property String id. To populate it with a custom UUID, I'd use a hibernate id generator instead of beforeInsert. Create a class that extends org.hibernate.id.IdentifierGenerator, then add an id generator mapping like this to your domain class:

class MyIdGenerator extends IdentifierGenerator {
    Serializable generate(SessionImplementor session, Object object) {
        return MyUUID.generate()
    }
}

class MyDomain {
    String id
    static mapping = {
        id generator:"my.package.MyIdGenerator", column:"id", unique:"true"
    }
}

这篇关于在Grails中将自定义ID生成定义为默认值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆