我正在将Grails应用程序从Oracle移植到MySQL数据库。原始的Oracle版本是一个旧数据库,它使用几个复杂的 View ,这些 View 利用了Oracle没有的MySQL的INSTEAD OF INSERT或UPDATE功能。作为一种解决方法,我在Domain类上实现了指向这些 View 的Insert和Update方法。例如,
class AdminUser {
//...
def update() {
if(this.validate()) {
Sql sql = Utils.getHibernateSql()
sql.execute(
"update table_x ...",
[...]
)
sql.execute(
"update table_y ...)",
[...]
)
sql.execute(
"update table_z ...",
[...]
)
return true
}
return false
}
//...
}
这是我目前遇到的问题的描述:
如何防止步骤3中发生神奇的保存(我最近读到某个地方,Grails将自动保存修改的Domain类实例,该实例在退出服务方法时尚未保存,但是我似乎找不到现在链接到该资源)?
最佳答案
您会将修改后的实例留在休眠 session 中,带有脏字段。休眠 session 刷新后,它将尝试使用通常的save()
方法再次保存该对象。
一种解决方案是在您手动保存更改后从休眠 session 中丢弃您的对象。例如:
def update() {
if(this.validate()) {
Sql sql = Utils.getHibernateSql()
sql.execute(
"update table_z ...",
[...]
)
...
this.discard() // remove the object from the hibernate session
return true
}
另外,您可以将其添加到Config.groovy以要求显式保存对象:
hibernate.flush.mode="manual"
关于grails - 自定义插入和更新方法被自动保存击败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3917161/