GORM Batch Deletes Made Easy with Load Method

29 / Sep / 2010 by Vivek Krishna 4 comments

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.

[java]
def sentMails = Mail.findAllByStatus("SENT")
sentMails*.discard() //detach all the objects from session
sentMails.each{
       Mail proxySentMailObject = Mail.load(it.id) //load proxy object
       proxySentMailObject.delete() //using the proxy object to delete from DB
}
[/java]
This also ensures that we don’t face the ConcurrentModificationException we would have faced if we tried deleting directly using
[java]
sentMails.each{
it.delete()
}
[/java]

Special Thanks to Amit for the wonderful post which was of great help!

Hope this helps
Vivek
vivek[at]intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Vivek Krishna

    Hi Kefir,

    Thanks for the feature on the new version of the Plugin. This will really make the job easier for those who do not want to save the emails, once they are sent. 🙂

    Reply
  2. Kefir

    Hello guys,

    I released new version 0.2.0 of Grails Asynchronous Mail plugin. In this version you can mark message for deleting after sent.

    You can set property

    asynchronous.mail.clear.after.sent=true

    in configuration file. Or add string

    delete true;

    in sentAsynchronousMail closure. Then message will be deleted after sent immediately.

    Reply

Leave a Reply to Kefir Cancel reply

Your email address will not be published. Required fields are marked *