GORM domain.delete(flush: true) 没有触发 HibernateException 或其他反馈?

GORM domain.delete(flush: true) not firing HibernateException nor other feedback?

鉴于:

Foo () {
  Bar bar

  static contraints = {
      bar (nullable: false)
  }
}

和管理 Bar 类型的服务,其中方法删除:

line 105: BarService {
line 106:     public BarCommand deleteBar(long Id) {    
line 107:         Bar b = Bar.get(Id)
line 108:         if (!b.delete(flush: true)) {
line 109:             //handle error here

如果存在一个现有的 Foo,"f" 已经有一个 id 1 的 Bar(例如)与之关联,那么第 108 行应该会失败并出现一些错误,解释 "b cannot be deleted, it is assigned to Foo id: 1" 但是,所有发生的情况是第 108 行 returns false on truthiness 并且不管删除是否成功都会进入错误处理。

我们如何知道删除域名是成功还是失败? doco 没有描述这一点 - Hibernate 报告应该触发 HibernateException,但在任何单元测试场景中都没有触发异常...

(http://docs.grails.org/latest/ref/Domain%20Classes/delete.html)

我意识到 domain.delete() 不会 return 任何东西,因为在刷新事件之前删除不会传达给数据库,所以我认为明确调用 flush: true 会解决这个问题,但它似乎没有。

就我个人而言,我不喜欢为了删除对象而从数据库中检索对象的效率低下,所以不要这样做:

Bar b = Bar.get(Id)
if (!b.delete(flush: true)) {
  // handle error here
}

我会使用 HQL 来执行删除,因为这样可以避免先检索它(load() 方法是另一种解决方案)。

Integer rowsDeleted = Bar.executeUpdate('delete Bar where id = ?', [Id])
if (!rowsDeleted) {
  // handle error here
}

这种方法的另一个好处是 executeUpdate returns 行数 updated/deleted,因此您可以检查操作是否 成功。

我已经在数据库中使用了事务提交更改,并且效果很好。

阅读 Object delete() in a controller no longer works without a Transaction as of 3.2.4 #10444 了解更多信息。

def delete(long id) {

    Document FSDocumentInstance = Document.get(id)
    Document.withTransaction {
        if (FSDocumentInstance == null) {
            return
        }
        File file = new File(FSDocumentInstance.filePath)
        File test = new File(FSDocumentInstance.fullPath)
        test.delete()
        file.delete()
        FSDocumentInstance.delete()
        flash.message = "File deleted"
    }
        redirect(action: 'index')
    }
}