Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Grails GORM Truncate Tables in H2
package com.jetbootlabs.services
/*
* Truncates H2 tables mapped by the domainClasses variable. Useful for cleaning up test data.
*
* Temporarily disables referential integrity to avoid constraint violation errors when
* deleting records.
*
* Inspired by Luke Daley's blog post on how to do this in MySQL:
* http://ldaley.com/post/398082618/brute-force-fixture-cleanup-in-grails
*/
class DataNukerService {
def sessionFactory
def dataSource
def grailsApplication
def execute() {
sessionFactory.currentSession.flush()
def db = new Sql(dataSource)
db.withBatch { stmt ->
stmt.addBatch("SET REFERENTIAL_INTEGRITY FALSE")
def domainClasses = grailsApplication.domainClasses*.clazz
domainClasses.each { domainClass ->
def metadata = sessionFactory.getClassMetadata(domainClass)
stmt.addBatch("TRUNCATE TABLE ${metadata.tableName}")
}
stmt.addBatch("SET REFERENTIAL_INTEGRITY TRUE")
}
sessionFactory.currentSession.clear()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.