简体   繁体   English

Grails 2.4.4将项目两次添加到一对多关系

[英]Grails 2.4.4 adds item twice to one-to-many relationships

I have two classes in my model: Contribution (a commit) and Version (a versioned object in the commit). 我的模型中有两个类:Contribution(提交)和Version(提交中的版本化对象)。 Contribution hasMany Version and Version belongsTo Contribution. 贡献有很多版本,而Version属于贡献。

When I "commit" a new version, it creates a new contribution, a new version and contribution.addToVersions(version). 当我“提交”一个新版本时,它将创建一个新的贡献,一个新的版本以及tribution.addToVersions(version)。 This does something like: 这样做像:

1. contribution = new Contribution(...)
2. newversion = new Version(contribution: contribution, ...)
3..9. ...
10. contribution.addToVersion(newversion)

If a previous version exists for the same object, I do: (this goes in the ... of the previous snipet) 如果同一对象存在先前版本,则执行以下操作:(这在先前代码段的...中)

3. if (Version.countByUid(newversion.uid) > 0) {
4.   prevVersion = Version.findBtUid(newversion.uid)
5.   prevVersion.lastVersion = false
6.   prevVersion.save() <<<< THIS IS ADDING THE newversion TO contribution.versions
7. 
8.   newversion.updateVersion() // updates the las part of the uid
9. }

The problem is when I receive a new version of an existing one, line 6. adds the new version to the contribution.versions (very weird), then on line 10. the version is added again to that collection, so I end up with duplicated items in contribution.versions. 问题是当我收到现有版本的第6行的新版本时,将新版本添加到tribution.versions中(非常奇怪),然后在第10行中,将该版本再次添加到该集合中,所以最终得到版本中的重复项。

Any ideas why this is happening? 任何想法为什么会这样? Why saving another instance of Version affects the relationship of the new version and the new contribution? 为什么保存版本的另一个实例会影响新版本和新贡献的关系?

My workaround was to just execute the addToVersions if there are not previous versions, but I want to know if this is actually a Grails bug buecause it doesn't make much sense. 我的解决方法是,如果没有以前的版本,只执行addToVersions,但是我想知道这是否实际上是Grails的错误,因为它没有多大意义。

The problem was the relationship between Version and Contribution is bidirectional, so when I set version.contribution and save the version, the version is added automatically by Grails to the contribution.versions list. 问题是Version和Contribution之间的关系是双向的,因此当我设置version.contribution并保存版本时,Grails会自动将版本添加到tribution.versions列表中。

So if I also do the contribution.addToVersions, I end up with the version added twice to the contribution.version list. 因此,如果我也进行了tribution.addToVersions,我最终会将版本两次添加到contribution.version列表中。

Possible solutions are: not doing the addToVersions, or making the relationship unidirectional. 可能的解决方案是:不执行addToVersions或使关系单向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM