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 ]