grails - 在 grails cmd 脚本中填充数据库
问题描述
我有一个包含许多 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 文件的目录路径,获取每个文件并对其进行处理,将其存储在数据库中。在我的 grails 项目中,我有一些域类,我正在使用 GORM 在我的数据库中检索和保存新对象。在我的 grails 脚本中访问我的域类并使用 GORM 方法将它们保存在我的数据库中是否可行?我已经尝试导入我的域类,但它不起作用。而且我在 grails 2.5 文档中找不到任何内容。
解决方案
请参阅https://github.com/jeffbrown/federicobaioccoscript上的项目。
脚本中的注释描述了正在发生的事情。
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
您将看到该脚本有效。
我希望这会有所帮助。
推荐阅读
- c - 字符串文字和数组的地址
- python - Pandas 面板数据 - 基于规则的值的线性插值
- clang - ctags 使用 llvm clang 时 clang_parseTranslationUnit 崩溃
- r - 如何将新列从另一个具有多个条件的数据帧添加到一个数据帧?
- c# - 适用于 eBay 的 .NET REST API(产品 API)
- mysql - 基于多列删除重复记录并在mysql中保留一条
- android - 如何根据动态数据获得具有 4 列和 2 行的水平滚动视图?
- javascript - 如果实际值大于 14 位,为什么 js 中的 parseFloat() 会舍入数字
- mongodb - MongoDB 聚合:将每个数组值从另一个字段添加到数组内的每个对象。合并/合并来自不同字段的两个数组
- vb.net - VB Express 2010 找不到我不想再找的文件