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

时间:2016-06-30 00:21:57

标签: grails gorm

Grails 3应用程序 - 我一直遇到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
}

在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.

我的断言失败可能是由我遇到的其他一些问题引起的,但我想验证跨越包裹边界是不应该受到责备的。

2 个答案:

答案 0 :(得分:2)

如果您在输入上面没有出错,那么您正在定义一个'motherClass'对象,但在ConfigFiles中将motherClass设置为'mother'对象。

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

通常,您会将子项添加到所有者类并保存所有者类,并将保存级联到子项。

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

答案 1 :(得分:1)

BootStrap.groovy中的断言失败是有道理的,因为当实体加载到Hibernate会话时,GORM会填充关联的hasMany集。但在此示例中,GORM不会自动搜索会话并将新保留的实体添加到其拥有实体的hasMany集中。

尝试另一方的断言。

assert ConfigFile.findAllByMotherClass(motherClass)

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