【问题标题】:correct way to implement delete feature in grails?在grails中实现删除功能的正确方法?
【发布时间】:2016-11-07 10:28:36
【问题描述】:

我有一个类似的删除方法

控制器方法

def deletemap(Long id){


    try {

        mapService.deleteMap(id)

    }
    catch (ValidationException e) {


        flash.message = "Sorry an error occured when deleting map!!"

        redirect(action: "maps", id: event.id)

        return


    }


    flash.message = "Map was deleted!!"

    redirect(action: "maps", id: event.id)

    return


}

控制器方法调用服务方法如下:

服务方式

def deleteMap(id){


    def map = Map.get(id)



    if(map == null){

            throw new org.springframework.security.access.AccessDeniedException("Id doesn't exist!!!")
            return
    }



    map.delete(flush: true)

}

我的目标是尽可能完成此功能。我目前正在编写一些测试,并且想知道当 map.delete(flush: true) 失败时我是否应该处理测试中的案例。当这个 gorm 调用失败时,会出现这种情况吗?我很感激任何帮助!谢谢!

【问题讨论】:

    标签: grails


    【解决方案1】:

    一个干净的方法:

    控制器

    def deletemap(Long id){
    
        Map mapInstance = Map.get(id)
    
        if (!mapInstance) {
            flash.message = "Map not found"
        }
        else {
            mapService.deleteMap(mapInstance)
            flash.message = "Map was deleted!!"
        }
    
        redirect(action: "maps")
    }
    

    服务

    def deleteMap(Map mapInstance){
        map.delete(flush: true)
    }
    

    如果Map与其他域有关系,则失败;在这种情况下,您需要验证关系是否存在并删除该关系或告诉您的用户关系阻止删除。但这取决于您的域设计。

    【讨论】:

    • 我们不应该也处理服务方法中删除失败的情况。即当此代码失败 map.delete(flush: true) 或抛出异常时。您的解决方案仅处理删除成功的情况。如果我错了,请纠正我。谢谢!
    • 如果数据库连接丢失,您可以添加一个 try/catch,但我认为如果是这种情况,您的应用程序可能会完全关闭。我的回答涵盖了两种常见的情况:未找到实例和在另一个关系中使用实例。
    • 我认为刷新不是强制性的。 delete() 也能达到目的吧?
    • 对。请记住If set to true the persistent context will be flushed resulting in the instance being deleted immediately.
    • 你知道 delete(failOnError: true) 是否是最好的,因为该操作发生在服务类中,因此异常会导致事务回滚。在 delete() 的情况下,我假设失败是静默发生的。
    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 2011-07-01
    • 2016-02-22
    • 2016-12-17
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2013-10-12
    相关资源
    最近更新 更多