在 Grails 中使用 Groovy Enum 作为 Id 字段
我们在 GORM 中有一些遗留数据库映射,其中一些有一个主键,它是一个枚举。枚举使用字符串值而不是序数存储。
例如:
class AccountingGLMap {
AccountingTypeCode id
String typeCode
static mapping = {
id(column: 'accountingTypeCode', generator: 'assigned')
}
}
当您尝试检索实例时,您会得到:
| Error 2012-02-23 10:32:41,319 [pool-5-thread-1] ERROR context.GrailsContextLoader - Error executing bootstraps: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
我已验证表中的值是否正确映射到给定的枚举中(只要它不是主键,我就可以使用枚举实例化对象)。如果我们将枚举更改为字符串,则一切正常。
我确实看到一篇文章声称在使用 JPA 时不能使用 Enum 作为主键,但即使这一点也存在争议。
有人有这样做的经验吗?
编辑:作为参考,我们针对 Oracle 数据库使用 2.0.1。
We have some legacy database mappings in GORM and several have a primary key which is an enumeration. The enumeration are stored using the string values, not the ordinals.
For example:
class AccountingGLMap {
AccountingTypeCode id
String typeCode
static mapping = {
id(column: 'accountingTypeCode', generator: 'assigned')
}
}
When you try to retrieve an instance, you get:
| Error 2012-02-23 10:32:41,319 [pool-5-thread-1] ERROR context.GrailsContextLoader - Error executing bootstraps: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
I have verified that the values in the table map properly into the enumeration given (I can instantiate the object with the Enum so long as it's not the primary key). If we change the Enum to a String, everything works fine.
I did see an article claiming you can't use an Enum as the primary key when using JPA, but even that was disputed.
Anyone have experience doing this?
EDIT: For reference we are using 2.0.1 against an Oracle database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
type: 'string'
添加到您的 id 映射中,然后为 id 添加一个接受 String 输入的 setter,如下所示:Add
type: 'string'
to your id mapping and then add a setter for id that takes a String input like so: