views:

386

answers:

2

I have a table which has records that need to be periodically cleared according to a set of criteria.

I was expecting that I could use the criteria builder to just delete the records, but that fails because there is no delete method on criteria...

def c = Agency.createCriteria()
c.delete
{
    eq("agency", "XXX")  
}

So I thought maybe I first query for the set and then delete that...

def c = Agency.createCriteria()
def deletions = c
{
    eq("agency", "XXX")  
}
deletions.delete

This also fails for the same reason, different object.

So what is the right way to do this? It seems excessive (perverse) that I would have to iterate through the entire result set calling delete() on each item.

I know I can form a query to execute directly either in HQL or SQL but that feels wrong too. Is the criteria builder only meant for retrieval?

Thanks

+4  A: 

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"])
Colin Harrington
yes, this is how I am doing it, but it is a bit crazy that I cannot use criteria. DELETE is a valid part of query semantics and supported by all RDBMSs and a perfectly valid thing to do, in spite of what the Hibernate/GORM authors may think. In my case it would be very bad practice to leave the out of date records in the table.
Simon
+1  A: 

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

def c = Agency.createCriteria().list {
    eq("agency", "XXX")  
}*.delete()
sbglasius
wow! what does that stray * do? I tried exactly this but without the * and got a compiler error...
Simon
The *. is the Groovy spread operator http://groovy.codehaus.org/Operators#Operators-SpreadOperator(.) In Sbglasius' example it calls the delete() method on item in the collection that was returned.
Colin Harrington