Grails isAttached() 和 attach()

Grails isAttached() and attach()

正在尝试使用

if(!musician.style.isAttached()){
    musician.style.attach();
}

代码记录 isAttached returns false。 但是,当它尝试 attach() 时,它给了我一个错误

"object with the same identifier value was already associated with the  session"

帮我理解一下。如果标识符已经与会话相关联,为什么 isAttached() 不 return TRUE 到会话?

更新:我认为 mohsenmadi 的回答很可能与您的问题相关 - 我错过了 style是关联的域对象。

如果没有看到您的更多代码,很难具体说明,但我怀疑您可能有具有相同标识符的重复对象,其中一个附加到您的会话,另一个不附加(这就是为什么 isAttached() 返回 false)。我在进行大量手动会话管理(例如,实施批处理)时看到过这种情况。

我也遇到了这个问题,理论在运行时没有按预期交付。我的解决方案类似于 musician.style = Style.get(styleId),您可以从 params 或您记得某处的地方获取 styleId。这当然可以正常工作,但它是一个 database/cache 调用,如果在循环内则不好。

当前会话中的所有实体都可以在

中找到
grails.util.Holders.grailsApplication.mainContext.sessionFactory.currentSession.persistenceContext.entitiesByKey