圣杯.调用保存后id为空 [英] Grails. Id is null after calling save

查看:42
本文介绍了圣杯.调用保存后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为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆