Grails/GORM是否允许在单独的java包中建立关系?

Grails/GORM是否允许在单独的java包中建立关系?,grails,gorm,Grails,Gorm,Grails3应用程序——我在Grails中的hasMany属性未填充方面遇到了问题。我刚刚意识到拥有类与拥有类位于不同的包中。通过跨越包边界进行关联,我是否在做一些愚蠢的事情 我正在做什么和观察什么的基本示例,如果没有意义: 拥有域类: package com.example.project import com.example.project.configuration.ConfigFile class MotherClass { String name static h

Grails3应用程序——我在Grails中的hasMany属性未填充方面遇到了问题。我刚刚意识到拥有类与拥有类位于不同的包中。通过跨越包边界进行关联,我是否在做一些愚蠢的事情

我正在做什么和观察什么的基本示例,如果没有意义:

拥有域类:

package com.example.project

import com.example.project.configuration.ConfigFile

class MotherClass {
    String name
    static hasMany = [ configFiles: ConfigFile ]
}
package com.example.project.configuration

import com.example.project.*

class ConfigFile {
    String name
    MotherClass motherClass
}
拥有的域类:

package com.example.project

import com.example.project.configuration.ConfigFile

class MotherClass {
    String name
    static hasMany = [ configFiles: ConfigFile ]
}
package com.example.project.configuration

import com.example.project.*

class ConfigFile {
    String name
    MotherClass motherClass
}
在Bootstrap.groovy中:

MotherClass motherClass = new MotherClass(name:"mother").save(failOnError: true)
new ConfigFile(name: "file1", motherClass: mother).save(failOnError: true)
new ConfigFile(name: "file1", motherClass: mother).save(failOnError: true)
assert motherClass.configFiles.size() > 0 #this assertion would fail
在随机服务中:

assert MotherClass.findByName("mother").configFiles.size() > 0 #this would fail too.

我的断言失败可能是由我遇到的其他问题引起的,但我想验证跨越包边界不是罪魁祸首。

BootStrap.groovy中的断言失败是有意义的,因为当实体加载到Hibernate会话中时,GORM会填充相关的,
hasMany
。但在本例中,GORM不会自动搜索会话并将新持久化的实体添加到其所属实体的
hasMany
集合中

请尝试从另一方的断言

assert ConfigFile.findAllByMotherClass(motherClass)

我知道这并不能解决您的问题,但希望它能为您指出正确的方向。

如果您在上面的键入中没有出错,那么您定义的是“motherClass”对象,但在ConfigFiles中,将motherClass设置为“mother”对象

我假设情况并非如此——那么,我认为您没有向Grails提供足够的关于所有者-子关系的信息

通常,您会将子类添加到owner类并保存owner类,然后让保存级联到子类

MotherClass mother = new MotherClass(name:"mother")
mother.addToConfigFiles(new ConfigFile(name: "file1", motherClass: mother))
mother.addToConfigFiles(new ConfigFile(name: "file1", motherClass: mother))
mother.save(failOnError: true)

理想情况下,您应该在ConfigFile端使用belongsTo子句,否则删除将不会级联。请参阅:

我将子项重构到同一个包中,问题仍然存在。所以我猜包边界不是真正的问题。一旦我找到答案,我会添加更多细节。来自另一方的断言确实有效。作为一种解决方法,我会很满意,但代码中有些地方向后走是很尴尬的。这似乎有点明显,但感谢您指出这一点。我认为保存一个引用到mother的configFile会导致GORM将该configFile添加到mother的集合中。如果GORM本质上执行一个新的查询来发现母亲的配置文件,而我不必显式地为此编写代码,那么会发生什么呢?(据我所知,它并不是查询数据库以查看哪些配置文件属于母亲,这就是为什么addToConfigFiles是必需的。)工作非常好。谢谢