grails cmd脚本中的访问域对象

问题描述 投票:0回答:1

我有一个包含许多json文件的文件夹。我需要处理这些文件并将它们存储在mysql数据库中。为此,我尝试创建grails cmd脚本(因为该项目使用的是Grails 2.5.6)。因此,我要做的第一件事是:grails create-script upload-json-files,然后grails创建了我的脚本,如下所示:

includeTargets << grailsScript("_GrailsInit")

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

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

setDefaultTarget(uploadJson)

[我希望我的脚本在args中获取所有JSON文件的目录路径,获取每个文件并进行处理,并将其存储在db中。在我的grails项目中,我有一些域类,并且我正在使用GORM来检索新的对象并将其持久保存在数据库中。在grails脚本中访问域类并使用GORM方法将其持久化在数据库中是否可行?我已经尝试导入我的域类,但是它不起作用。而且我在grails 2.5文档中找不到任何内容。

grails cmd scripting gorm grails-2.5
1个回答
0
投票

请参见https://github.com/jeffbrown/federicobaioccoscript处的项目。

脚本中的注释描述了正在发生的事情。

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)

如果克隆该仓库并运行./grailsw populate-db,您将看到脚本起作用。

我希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.