6.3.2 Deleting Objects 3.0.10

See the light - agile, industrial strength, rapid web application development made easy

(Quick Reference) # 6.3.2 Deleting Objects - Reference Documentation Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari Version: 3.0.10 ## 6.3.2 Deleting Objects An example of the delete method can be seen below:
    def p = Person.get(1)
    p.delete()
As with saves, Hibernate will use transactional write-behind to perform the delete; to perform the delete in-place you can use the `flush` argument:
    def p = Person.get(1)
    p.delete(flush: true)
Using the `flush` argument lets you catch any errors that occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a `DataIntegrityViolationException` that is thrown when you violate the database constraints:

    def p = Person.get(1)try {
        p.delete(flush: true)
    }
    catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "Could not delete person ${p.name}"
        redirect(action: "show", id: p.id)
    }
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"])
| Quick Reference (hide)