当我将实例另存为时:
test.save()
保存可能会失败。我可以
if (!test.save(flush:true) {
// save failed
}
考虑到这种情况,我从另一个函数中获得了一个实例,但无法执行此检查,因为我不会再次保存该实例。
是否可以检查实例是否仍保留在数据库中或处于未保存状态?
最佳答案
我知道这是一个老问题,但是为了以后引用,我认为适当的答案是这样的:
鉴于OP的原始问题
Is there a way to check if an instance is still persisted in the data base or has the unsaved state?
就在这里。调用实例的域类的exist()方法。
假设我们有一个Test域类和一个测试对象实例:
def bPersists = ( test.id != null && Test.exists(test.id) ); // Check test.id for null because a id of zero is a valid index, also the id might not be an integer.
请注意检查test.id是否等于null,而不只是检查它的评估结果是否为true。那是因为一个等于零的id的取值为false,但实际上它是一个有效的id号。另外,id可以是字符串或其他数据类型。
关于grails - 如何使用GORM测试实例是否在数据库中持久存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24996250/