Заполните базу данных в скрипте Grails CMD - PullRequest
0 голосов
/ 07 февраля 2020

У меня есть папка с множеством json файлов. Мне нужно обработать эти файлы и сохранить их в базе данных mysql. Для этого я пытаюсь создать скрипт 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)

Я хочу, чтобы мой скрипт получил в аргументах путь к каталогу со всеми файлами JSON , взять каждый файл и обработать его, сохраняя его в БД. В моем проекте grails у меня есть несколько классов доменов, и я использую GORM для извлечения и сохранения новых объектов в моей базе данных. Реально ли получить доступ к моим классам домена в моих скриптах Grails и использовать методы GORM для сохранения их в моей базе данных? Я уже пытался импортировать свои доменные классы, и это не сработало. И я не могу найти ничего в Grails 2.5 документа.

1 Ответ

1 голос
/ 08 февраля 2020

См. Проект на 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, вы увидите, что скрипт работает.

Надеюсь, это поможет.

...