2

所以我有 3 个域,Feed,SourceArticle. 它们的设置与此类似,尽管我删除了所有未描述其关系的成员

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,我能够加载 aFeed并验证它确实包含 1 Source,并且它Source 有 2 Articles。

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但没有帮助。我究竟做错了什么?

4

1 回答 1

0

所以这就是我最终为解决我的问题而做的事情......

如问题中所述,an Feedhas many Sources which has many Articles。yaml 文件与问题中所述相同。对于我的Feed我添加

static mapping = {
    sources cascade: "all"
}

对于我添加的来源

static mapping = {
    articles cascade: "all"
}

用于将yaml文件加载到DB的groovy代码如下

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)
    }
}

请让我知道是否有其他方法可以做到这一点,因为这可能不是最好的解决方案。

于 2014-05-02T12:33:28.787 回答