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

Does Grails / GORM permit relationships in separate java packages?

Grails 3 应用程序——我一直遇到 Grails 中的 hasMany 属性 未填充的问题。我刚刚意识到拥有的 class 与拥有的 class 在不同的包中。我是不是通过跨包边界关联做了一些愚蠢的事情?

我正在做和观察的基本示例,以防没有意义:

拥有域Class:

package com.example.project

import com.example.project.configuration.ConfigFile

class MotherClass {
    String name
    static hasMany = [ configFiles: ConfigFile ]
}

拥有的域Class:

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 中断言的失败是有道理的,因为 GORM 填充关联的 hasMany,设置实体何时加载到 Hibernate 会话中。但在此示例中,GORM 不会自动搜索会话并将新持久化的实体添加到其拥有实体的 hasMany 集中。

试试另一边的断言。

assert ConfigFile.findAllByMotherClass(motherClass)

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

如果您在上面输入时没有犯错,那么您定义的是 'motherClass' object,但在 ConfigFiles 中将 motherClass 设置为 'mother' object。

我认为情况并非如此 - 那么,我认为您没有向 Grails 提供有关 owner-child 关系的足够信息。

通常您会将 children 添加到所有者 class 并保存所有者 class 并让保存级联到 children。

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 子句 - 否则删除不会级联。参见:http://docs.grails.org/3.1.1/ref/Domain%20Classes/belongsTo.html