How do you bulk delete records in Grails/GORM?

夙愿已清 提交于 2019-12-03 02:26:26
Colin Harrington

From the User Guide about deleting objects:

Note that Grails does not supply a deleteAll method as deleting data is discouraged and can often be avoided through boolean flags/logic.

If you really need to batch delete data you can use the executeUpdate method to do batch DML statements:

Customer.executeUpdate("delete Customer c where c.name = :oldName", [oldName:"Fred"])

With Grails 2.0 you can use a detached query like this:

Agency.where { }.deleteAll()

Note that you don't get the listeners and whatnot executed, but it does execute through to the database, AND it is compatible with the mocked domain stuff, as in:

void testWhatever() {
    mockDomain(Agency, [])
    saveABunchOfAgencies() // saves 10 of 'em
    assert Agency.count() == 10

    Agency.where { }.deleteAll()

    assert Agency.count() == 0   // Joy!
}

That being said the GORM unit test mocks have a bunch of gotchas but are in general pretty neat.

sbglasius

If you want to avoid HQL I'd suggest using GORM list(), delete() and Groovy's spread operator:

def agencyList = Agency.createCriteria().list {
    eq("agency", "XXX")  
}
agencyList*.delete()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!