grailscmdscriptinggrails-ormgrails-2.5

Populate database in grails cmd script


I have a folder with many json files. I need to process these files and store them in a mysql database. In order to do that, I am trying to create a grails cmd script (since the project is using Grails 2.5.6). So, first thing I did was: grails create-script upload-json-files, then grails created my script that looks like this:

includeTargets << grailsScript("_GrailsInit")

target(uploadJson: "The description of the script goes here!") {
    doStuff()
}

target (doStuff: "The implementation task") {
}

setDefaultTarget(uploadJson)

I want my script to get in the args the directory path with all the JSON files, take each file and proccess it, storing it in a db. In my grails project I have some domain classes and I am using GORM to retrieve and persist new objects in my database. Is it feasible to access to my domain classes in my grails scripts and use GORM methods to persist them in my db? I already tried to import my domain classes and it didn't work. And I can't find anything in the grails 2.5 docs.


Solution

  • See the project at https://github.com/jeffbrown/federicobaioccoscript.

    The comments in the script describe what is going on.

    https://github.com/jeffbrown/federicobaioccoscript/blob/977df5aedff04cec47d8c25900b4048cf1e12fe8/scripts/PopulateDb.groovy

    includeTargets << grailsScript('_GrailsBootstrap')
    
    target(populateDb: "Target demonstrates one approach to using domain classes in a script") {
        depends classpath, bootstrap
    
        // load the Person class
        def personClass = classLoader.loadClass('federicobaioccoscript.Person')
    
        // the question is about using domain classes in a script, not
        // about parsing JSON files so here the peopleData is hardcoded instead
        // of complicating the example with file i/o.
        def peopleData = []
        peopleData << [firstName: 'Geddy', lastName: 'Lee']
        peopleData << [firstName: 'Neil', lastName: 'Peart']
        peopleData << [firstName: 'Alex', lastName: 'Lifeson']
    
        // create and persist instances of the Person class
        personClass.withNewSession {
            peopleData.each { personData ->
                // create an instance of the Person class
                def person = personClass.newInstance personData
    
                // save the instance to the database
                person.save()
            }
        }
    
        // this is only here to demonstrate that the data
        // really is in the database...
        personClass.withNewSession {
            List people = personClass.list()
    
            println people
        }
    }
    
    setDefaultTarget(populateDb)
    

    If you clone that repo and run ./grailsw populate-db you will see the script works.

    I hope that helps.