圣杯.调用保存后id为空

本文介绍了圣杯.调用保存后id为空的处理方法,对大家解决问题具有一定的参考价值

问题描述

我已经对此进行了搜索,但仍然无法弄清楚我做错了什么.调用 save() 后,域对象 idnull.

I've already searched about this, but still cannot figure out what I'm doing wrong. After calling save() the domain object id is null.

我已经读过,如果保存对象时出现问题,就会发生这种情况,如果是这种情况,save(flush:true) 应该会抛出错误,但事实并非如此.看看我的代码和输出:

I've read it'll happen if there's a problem when saving the object, and that save(flush:true) should throw an error if that's the case, but it's not. Look at my code and the output:

def pic = new Picture(title:'XX', path:"XXX")
album.addToPictures(pic).save()
if(pic.validate())
   println "no errors. New id: " + pic.id
else
   println "with errors"

输出:

no errors. New id: null

当使用flush:true时

And when using flush:true

def pic = new Picture(title:'XX', path:"XXX")
album.addToPictures(pic).save(flush:true)
if(pic.validate())
   println "no errors. New id: " + pic.id
else
   println "with errors"

输出:

no errors. New id: 17

如您所见,创建对象没有任何错误,我应该能够在调用 save() 后获取对象的 id.有什么想法吗?

As you can see, there aren't any errors creating the object, and I should be able to get the id of the object after just calling save(). Any ideas?

谢谢

推荐答案

您误解了对象实际持久化到数据库的时间.当你调用 obj.save() 时,一个对象不会被持久化,它会在以下任何一个先发生时被持久化:

You are misunderstanding the timing of when an object actually gets persisted to the database. An object does not get persisted when you call obj.save(), it gets persisted when whichever of the following happens first:

  • 调用 save() 的事务已提交
  • 调用 save() 的 Hibernate 会话已关闭

可以显式启动事务

SomeDomainClass.withTransaction {
  // code in here runs within a transaction
}

通常,每次调用服务方法时也会隐式启动事务

Normally, a transaction is also implicitly started for each call to a service method

class MyService {

  void doSomething () {
    // code in here runs within a transaction
  }  
}

如果您不显式或隐式使用事务,则保存的对象会在 Hibernate 会话关闭时(大致)在 HTTP 请求完成时持久化.

If you don't explicitly or implicitly use transactions, saved objects get persisted when the Hibernate session closes, which is (roughly) when the HTTP request completes.

然而,如果你调用 someObject.save(flush: true) 你是在告诉 Hibernate 立即持久化对象,这就是为什么

However, if you call someObject.save(flush: true) you are telling Hibernate to persist the object immediately, which is why

album.addToPictures(pic).save(flush: true)

Picture 实例分配一个 ID,但是

assigns an ID to the Picture instance, but

album.addToPictures(pic).save()

仅在封闭会话/事务关闭/提交时分配 ID

will only assign the ID when the enclosing session/transaction is closed/committed

继续您的评论

问题是我想使用 id 作为我需要保存的文件名的一部分.如果我在保存文件时遇到错误怎么办?我应该使用显式事务并将其回滚吗?

The problem is that I want to use the id as part of the name of a file I need to save. What about if I get an error saving the file? Should I use a explicit transaction and roll it back?

是的,使用显式事务,并在确定对象已成功持久化后保存文件,如果持久化失败则回滚事务

Yes, use an explicit transaction, and save the file once you're sure the object has been successfully persisted, roll the transaction back if persistence fails

def pic = new Picture(title:'XX', path:"XXX")

Picture.withTransaction { TransactionStatus status ->        

  try {
    album.addToPictures(pic).save()

  } catch(ex) {
    status.setRollbackOnly()
    throw ex
  }
}

// At this point you can be sure pic has been persisted, so use pic.id to save the file

更新 2

进一步的评论

一旦确定对象已成功保存,我就不想保存文件,但相反,我想在文件成功保存后保存对象.因此,我将把我的问题重新表述为有没有办法配置 Grails,以便在对象有效保存到数据库中之前知道要分配给新对象的 id?"

I don't want to save the file once I'm sure the object has been successfully persisted, but the opposite, I want to persist the object once the file has been successfully saved. So, I'm going to reformulate my questions as "Is there a way to configure Grails so that I can know the id that's going to be assigned to the new object before the object is effectively saved in the database?"

你已经知道了

album.addToPictures(pic).save(flush:true)

将为您提供 Picture 实例的 ID,因此如果您在事务中执行此操作,则无需实际提交事务即可获得 ID.但是,我认为这仅在您使用使用序列的数据库(Oracle,Postgres)时才有效.像下面这样的东西应该可以工作

will provide you with the ID of the Picture instance, so if you do this within a transaction you can get the ID without actually committing the transaction. However, I think this will only work if you're using a database that uses sequences (Oracle, Postgres). Something like the following should work

Picture.withTransaction { TransactionStatus status ->        

  try {
    def pic = new Picture(title:'XX', path:"XXX")  
    album.addToPictures(pic).save(flush: true)

    // pic.id should now be assigned, so save the file. I'm assuming an
    // an exception will be thrown if saving the file fails

  } catch(ex) {
    // you may also want to try rolling back the file save here, i.e. delete it
    status.setRollbackOnly()
    throw ex
  }
}

这篇关于圣杯.调用保存后id为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1173

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1071

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:808

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:900

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:930

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:877

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:865

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:834

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1734

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1309