Grails GORM 字段初始化问题
所以我有一个 1:1 的关系:
class Number1 {
Number2 n2
}
class Number2 {
belongsTo = [n2: Number2]
}
现在,我想在 Number1 类中初始化 n2,如下所示:
class Number1 {
Number2 n2 = New Number2(...).save()
}
但是 Grails 因休眠异常而失败。使用这种关系初始化字段的最佳实践是什么?
So I have a 1:1 relationship:
class Number1 {
Number2 n2
}
class Number2 {
belongsTo = [n2: Number2]
}
Now, I want to initialize n2 in class Number1 like:
class Number1 {
Number2 n2 = New Number2(...).save()
}
But Grails is failing with hibernate exceptions. What's the best practice here for initializing a field with this relationship?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这里有一个错误。正如您的问题所述,Number2 应该属于 Number1,而不是它本身:
如果您定义 Number2
belongsTo
Number1,则 Number2 的对象如果没有关联的 Number1 对象,将无法持久化。您必须首先将 Number2 对象添加到某个 Number1 对象。在控制器中执行类似的操作:
您应该查看 GORM 陷阱系列了解更多详情。它将展示在使用 Grails 持久性时如何避免非常常见的错误。
I presume there is a mistake here. As your question state, a Number2 should belongsTo Number1, not itself:
If you define Number2
belongsTo
Number1, an object of Number2 will not be able to persist if it has no associated Number1 object. You must add Number2 object to some Number1 object first.Do something like this in a controller:
You should check out GORM Gotchas series for more details. It will show how to avoid very common mistakes when doing with Grails persistence.