grails - 从YAML通过关联加载GORM

标签 grails groovy gorm grails-2.0 snakeyaml

所以我有3个域,FeedSourceArticle。他们的设置与此类似,尽管我删除了所有不描述其关系的成员

class Feed {
static hasMany = [sources:Source]
    static constraints = {
    }
}

class Source {
static belongsTo = [feed:Feed]
static hasMany = [articles:Article]
    static constraints = {
    }
}

class Article {

static belongsTo=[source:Source]

    static constraints = {
    }
}

在我的Bootstrap.groovy文件中,加载一个看起来像这样的YAML文件(请注意,上面引用的域是代码段)
--- !!com.my.package.model.Feed
  name: FeedName
  sources: 
  - !!com.my.package.model.Source
    link: "http://some.website.com"
    description: "Description"
    articles: 
    - !!com.my.package.model.Article 
      title: "We know quitting is tough but stay strong! We all have bad days, and you will get through this. Do whatever to boost your mood-just do not smoke."
    - !!com.my.package.model.Article 
      title: "Keep staying strong & smokefree--you can do it! We know it is not easy but it is worth it. Check Smokefree.gov for new tools, apps, and contests."

使用SnakeYAML,我能够加载Feed并验证它确实包含1 Source,并且Source具有2 Article
Object data = yaml.loadAll(new FileInputStream(servletContext.getRealPath('/path/to/yaml/file.yml')));
(data as Feed).save(failOnError: true)

我尝试保存会产生此错误:
Error |
2014-03-14 12:23:38,861 [localhost-startStop-1] ERROR hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
Message: null id in com.my.package.model.Source entry (don't flush the Session after an exception occurs)

我也尝试过使用flush:false保存,但这无济于事。我究竟做错了什么?

最佳答案

所以这就是我最终要解决的问题。

如问题所述,Feed具有许多Source,而Article具有许多。 yaml文件与问题中所述的文件相同。对于我的Feed,我添加了

static mapping = {
    sources cascade: "all"
}

对于我添加的来源
static mapping = {
    articles cascade: "all"
}

用于将yaml文件加载到数据库的常规代码如下
for (Object data : yaml.loadAll(new FileInputStream(servletContext.getRealPath('/WEB-INF/seeds/quitsmart.yml')))) {
    for (Source source : (data as Feed).sources) {
        for (Article article : source.articles) {
                source.addToArticles(article)
            }
            (data as Feed).addToSources(source)
        }
        (data as Feed).save(failOnError: true)
    }
}

请让我知道是否还有其他方法可以这样做,因为这可能不是最佳解决方案。

关于grails - 从YAML通过关联加载GORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22412717/

相关文章:

grails - GORM在调用beforeInsert方法之前检查约束

grails - GORM-表的层次结构-如何在域类中更改表名

grails - Grails Assets 目录管理

postgresql - 使用 postgres test-app 从 Grails 2.1.0 升级到 2.3.7 正在中断

grails - 向公历添加小时的问题

java - 想法 "Groovyc: unable to resolve class"- 在命令行上工作

java - Groovy 每个方法都返回不正确的结果

mysql - 保存的 GORM 域对象未显示在 mysql 中

jenkins - jenkins 脚本 dsl 中的 $class 语法

mongodb - GORM-获取域类属性的原始DB值