We are using the grails asynchronous mail plugin in our project and noticed that the sent mails never gets deleted from the database. This was an issue because we were sending out a lot of mails and all of them had PDF attachments of about 500 KB to 1 MB each. A sure recipe for disaster because our DB was growing exponentially. To take care of this, we decided to do a DB cleanup and delete the messages that had the status SENT.
Going through the documents for Deleting Objects, we noticed that grails doesn’t really support batch deletes. The executeUpdate() method, which was provided there as a workaround, was also not a suitable solution because we would’ve had to delete the associations explicitly. This is because executeUpdate() wasn’t doing anything with the associations, which in our case where the attachments.
We found a suitable solution after going through Amit’s blog about loading proxy objects. What we did was something like this.
def sentMails = Mail.findAllByStatus("SENT")
sentMails*.discard() //detach all the objects from session
Mail proxySentMailObject = Mail.load(it.id) //load proxy object
proxySentMailObject.delete() //using the proxy object to delete from DB
This also ensures that we don’t face the ConcurrentModificationException we would have faced if we tried deleting directly using
Special Thanks to Amit for the wonderful post which was of great help!
Hope this helps