grails 中的字符串 ID - 到底是如何做到的?
有人可以告诉我在 grails 中将字符串类型字段设置为 ID 的清晰、完整、100% 工作方式吗?我已经阅读了文档,然后阅读了网络上所有类似的咆哮,但未能创建一个工作原型。
这是我的尝试之一,目的是让您相信我不仅仅是懒惰地等待有人来做这项工作)))
class User {
String login
static hasMany = [apps : Application]
static constraints = {
}
static mapping = {
id generator: 'assigned', name: "login"
}
}
Can somebody show me clear, complete, 100% working way to set string-typed field as ID in grails? I've read the docs, then read all similar ranting on the web, but failed to create a working prototype.
Here is one of my attempts to make you believe I'm not just lazily waiting for somebody to do the job )))
class User {
String login
static hasMany = [apps : Application]
static constraints = {
}
static mapping = {
id generator: 'assigned', name: "login"
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用自然ID时,您必须使用 findBy 方法 此测试中演示的 get 方法:
而不是 可以使用单个字段 复合id映射:
注意需要复合 id 域类实现可序列化。
复合 id 将是:
When you use a natural id you have to use the findBy method instead of the get method as demonstrated in this test:
Alternately you could use a single field composite id mapping:
Note that composite id domain classes are required to implement Serializable.
The test for the composite id would be:
我假设您正在讨论将字符串主键(通常是自然键)映射到 grails 域对象中的主键。
这个答案来自于这里找到的信息:
http://dsommerville.blogspot.com/2009/09 /mapping-natural-keys-using-gorm.html
在这里:
http://gr8fanboy.wordpress.com/2010/04/08/adding-a-natural-key-to-a-database-table-using-straight-gorm/
对于例如,您有一个使用以下模式定义的用户表:
要在 grails 中执行此操作,您必须稍微调整一下定义。
首先,您必须将 id 映射到数据库中的给定列。 “分配”生成器
后,为了可用性,您可能需要添加瞬态字段 username ,以便可以使用 user.username = 。否则,我相信你必须使用 id 访问该字段。
此瞬态属性的 getter 和 setter 设置适当的“id”字段,从而更新数据库。
注意:脚手架无法识别瞬态字段,因此如果您希望代码更紧密地模拟数据库,则必须使用生成的控制器/视图。
I'm assuming you are talking about mapping a String primary key (normally a natural key) to the primary key in a grails domain object.
This answer is derived from information found here:
http://dsommerville.blogspot.com/2009/09/mapping-natural-keys-using-gorm.html
and here:
http://gr8fanboy.wordpress.com/2010/04/08/adding-a-natural-key-to-a-database-table-using-straight-gorm/
For example, you have a table Users defined with the following schema:
To do this in grails, you have to massage the definition a little.'
First, you have to map the id to the given column in your database. With a generator "assigned"
Then, for usability, you may want to add the transient field username so that you can use user.username = . Otherwise, I believe you'd have to access the field using id.
The getter and setter for this transient property set the appropriate "id" field, which in turn updates the database.
Note: Scaffolding doesn't recognize the transient field, so you'll have to work the generated controllers/views if you want your code to more closely model your db.