所以我有3个域,Feed
,Source
和Article
。他们的设置与此类似,尽管我删除了所有不描述其关系的成员
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/