首页 > 解决方案 > 在gorm中创建查询删除

问题描述

早上好,我需要在 Grails Hibernate (Gorm) 中执行 SQL 服务器的以下查询。我不明白如何执行顶部的查询

("delete CORE_NOTIFICATIONS where id in (select top 1000 ID form CORE_EVENT where date <10)")

在gorm中我这样做了,但它给出了错误

query = "delete CoreNotifications CN where CN.event_id in (select top? ID from CoreEvent CE where CE.date <?)"
res = CoreNotifications.executeUpdate (query, params)

我的错误是什么?

标签: grailsgrails-orm

解决方案


以我的经验,您很可能使用 GORM 来删除感兴趣的记录。下面是我过去对我的项目所做的代码片段。正如您在下面的评论中提到的,建议使用并行性,因为该表包含三百万条记录。

Date specifiedDate = Date.parse("yyyy-MM-dd hh:mm:ss", "2010-04-03 1:23:45") // pass your date here by extrating from params
def result = CoreEvent.where { date < specifiedDate }
List<Integer> iDs = result.list(sort: "date").collect { it.id }

GparsPool.withPool {

   iDs.eachParallel {
      // we need to wrap inside a single transaction for parallelism
      CoreNotifications.withTransaction {
         CoreNotifications.where { id == it }.deleteAll()
      }
   }
}

我希望这段代码能帮助您按预期解决问题。


推荐阅读