Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Grails在使用关系映射时按id获取_Grails_Persistence - Fatal编程技术网

Grails在使用关系映射时按id获取

Grails在使用关系映射时按id获取,grails,persistence,Grails,Persistence,使用这些域类: class Country { static hasMany = [states:State] } class State { static belongsTo = [country: Country] } 我无法通过其id检索状态 def country = new Country() def state = new State() country.addToStates(state) country.save() def foundState = Sta

使用这些域类:

class Country {
    static hasMany = [states:State]
}

class State {
    static belongsTo = [country: Country]
}
我无法通过其id检索状态

def country = new Country()
def state = new State()
country.addToStates(state)
country.save()

def foundState = State.get(state.id)

foundState为空。从数据库中检索状态的正确方法是什么?

缺少关键字
static
,并且存在按状态分类的打字错误(末尾没有
s
),应为:

static hasMany = [ states:State ]


您可能在某个地方验证失败。执行
.save(failOnError:true)
并查看是否出现异常


此外,在hibernate实际执行插入操作之前,您将没有ID。要立即触发此操作,请在
country.save()之后执行
.save(flush:true)
调用
state.refresh()
从数据库获取其最新状态。这是必要的,因为您没有显式地调用state.save()
(并且不应该这样做)。

在将域类链接到一起之前,尝试保存()域类,例如:
new Country().save()
在save方法中添加一个标志:
save(failOnError:true)
,如果Grails有任何抱怨。我想,你的域类真的不是空的,不是吗?
static belongsTo = [ country:Country ]