Initial/Test Data in Grails

on Wednesday 19 June 2013
When restarting my Grails application in development mode, it was becoming a pain to re-enter the test data to show people how the application worked.

Groovy provides great support for XML, and so using that for loading data was a no brainer.

First step, create a service:

 class LoadDbService {  
      def fileName  
      LoadDbService(def fileName) {  
           this.fileName = fileName  
      }  
      def load (){  
          ... detailed below ...            
      }  
 }  

This service is called from within BootStrap.groovy:

 class BootStrap {  
   def init = { servletContext ->  
           environments {  
                development {  
                     def dbs = new LoadDbService('grails-app/resources/test_data/test_records.xml')  
                     dbs.load()  
                }  
           }            
   }  

This service imports XML data into domain objects. If a domain object refers to another domain object, we user the power of GORM findBy. The implementation of load() is shown below:

 def data = new XmlSlurper().parse(fileName)  
 // These do not have dependencies and can therefore be generated easily  
 data.Release.each {  
      new Release(name: "${it.'@name'}", status: "${it.'@status'}", createdDate: new Date().parseToStringDate("${it.'@createdDate'}")).save(failOnError: true)  
 }  
 data.Stack.each {  
      new Stack(number: "${it.@'number'}").save(failOnError: true)  
 }  
 // for these imports to work correctly they need to search for the items that they relate to using .findByName  
 data.Version.each {  
      new Version(appName: "${it.@'appName'}", tag: "${it.@'tag'}", createdDate: new Date().parseToStringDate("${it.'@createdDate'}"), partOf: Release.findByName("${it.@'partOf'}")).save(failOnError: true)  
 }  
 data.Environment.each {  
      new Environment(hostname: "${it.@'hostname'}", testTier: "${it.@'testTier'}", lastRefresh: new Date().parseToStringDate("${it.'@lastRefresh'}"), ownedBy: Release.findByName("${it.@'ownedBy'}"), partOf: Stack.findByNumber("${it.@'partOf'}")).save(failOnError: true)  
 }       

And finally an example dataset:



Unfortunately, because of the format of XML conflicting with HTML I've had to provide a screenshot.

Inspiration taken from Sanjay Mysoremutt's Blog

0 comments:

Post a Comment