Question

I have a bunch of data that exists in a separate file and am trying to figure out how to automatically load this data into the db when the grails application starts up.

Was it helpful?

Solution

I put the json file into grails-app/conf/resources and edited Bootstrap.groovy.

At the top of the file, I injected the grails application:

class BootStrap {
    def grailsApplication
    ...

And later on I loaded the data:

if (!Cars.count()) {
        // add cars
        def filePath = "resources/carsData.json"
        def text = grailsApplication.getParentContext().getResource("classpath:$filePath").getInputStream().getText()
        def json = JSON.parse(text)

        for (carData in json) {
            def c = new Cars(
                name: carData ["name"],
                year: carData ["year"]
            ).save(failOnError: true);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top