如何使用 Grails 将新的自动生成的主键字段添加到旧表中?
我有一个遗留表,我正在尝试将其与 Grails 连接起来。我将简化它的模型以使事情变得更容易。表中有 2 个字段:字符串类型的“NAME”和整数类型的“CPAR”,其作用类似于表的 ID(主键)。
我想要做的是保留“CPAR”以实现向后兼容性,并将新字段“ID”插入将自动生成的表中,该字段实际上是表的主键。
这是我的域类:
Class Partners {
Long id
String name
Integer cpar
static mapping = {
table "PARTNERS"
version false
columns {
id column: "ID", generator: "sequence"
name column: "NAME"
cpar column: "CPAR"
}
}
}
当我运行此应用程序时,它确实在表中创建 ID 字段,但所有行都填充为零(“ID”字段为零,而不是整行)。当尝试通过其脚手架 Web 界面访问应用程序时,出现错误:无法在 null 对象上获取属性“id”。我想要的是让这些“ID”字段填充正确的值而不是零。我怎样才能做到这一点?我使用的数据库是Firebird。
I have a legacy table I'm trying to hook up with Grails. I'm going to simplify it's model to make things easier. There are 2 fields in the table: "NAME" which is of type string and "CPAR" which is of type Integer and acts like a table's ID (primary key).
What I want to do is keep "CPAR" for backwards compatibility and insert a new field "ID" into the table that will be auto generated and actually be table's primary key.
Here is my domain class:
Class Partners {
Long id
String name
Integer cpar
static mapping = {
table "PARTNERS"
version false
columns {
id column: "ID", generator: "sequence"
name column: "NAME"
cpar column: "CPAR"
}
}
}
When I run this application it does create ID field in the table but all rows are populated with zeroes (The "ID" field is zero, not the whole row). When trying to access application via it's scaffolded web interface it gives me error: Cannot get property 'id' on null object. What I would like is to have those "ID" fields populated with proper values instead of zeroes. How can I accomplish this? Database I'm using is Firebird.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不熟悉 Firebird,但我假设它使用类似于 Oracle 和 MySql 的序列。我看到的第一个问题是
Long id
的声明。 Hibernate 为您提供了 id,因此您不需要这行代码。接下来,您可以指定定义列时要使用的顺序。我从未使用过
columns{}
闭包,我总是在mapping{}
闭包内完成所有列映射,所以我不能 100% 确定上面的代码会起作用。如果没有,您可以将生成器和名称移到列{}
之外,它应该可以工作:本文专门讨论映射旧表:
http://dave-klein.blogspot.com/2008 /03/grails-orm-dsl-rules.html
这是关于映射 ID 的 Grails 文档,它并没有真正讨论序列名称:
http://grails.org/doc/latest/ref/Database%20Mapping /id.html
I'm not familiar with Firebird, but I'd assume it uses sequences similar to Oracle and MySql. The first problem that I see is the declaration of
Long id
. Hibernate provides the id for you so you don't need this line of code. Next you can specify the sequence that you want to use when you define the column.I've never used the
columns{}
closure I always have just done all of my column mapping inside of themapping{}
closure, so I'm not 100% sure the above code will work. If it doesn't you can move the generator and name outside of thecolumns{}
and it should work:This article talks specifically about mapping legacy tables:
http://dave-klein.blogspot.com/2008/03/grails-orm-dsl-rules.html
This is the Grails doc on mapping IDs which doesn't really talk about sequence name:
http://grails.org/doc/latest/ref/Database%20Mapping/id.html