【问题标题】:Grails -- Issue with secondary keyGrails - 辅助键问题
【发布时间】:2011-03-11 07:53:38
【问题描述】:

我有一个名为 OrgUnit 的实体,定义如下

class OrgUnit {

String name
String description
.....
.....
static belongsTo = [workSpace:WorkSpace]
static constraints = {
    //enforce uniqueness of the OrgUnit Name within a WS.
    name(nullable: false, blank: false, unique: 'workSpace')
    address(nullable:true)
    }
...
...

}

在我的服务班里..

def updateOrgUnit(OrgUnit orgUnit) {
    //The DB query generated by GORM here is wrong...
    OrgUnit mergedOu = OrgUnit.merge(orgUnit);

    try
    {
        if (!mergedOu.save(flush:true)) {
                        mergedOu.errors.allErrors.each{error ->
                        println "An error occured while saving 'orgUnit': ${error}"
                        errorMsg = "Exception occurred while executing updateOrgUnit()";
                    }
        }
    }
    catch (Exception exc)
    {
        exc.printStackTrace();
    }

}

我尝试更新的 OrgUnit 的名称和其他一些详细信息已更改。 这似乎是一个非常简单的更新,但它不起作用。原因是,作为合并的一部分,Grails 尝试根据“OrgUnit Name + WorkSpace Id”的组合检索实体,该组合是辅助键,而不是 OrgUnit 实体的主键字段“Id”。而且由于名称是一个已更改的字段,因此生成的查询无法检索任何内容,提交无声无息地失败,我一点也不例外。

这是作为合并操作的一部分生成的数据库查询..

select this_.id as id18_0_, this_.version as version18_0_, this_.address_id as address3_18_0_, this_.archive as archive18_0_, this_.name as name18_0_, this_.org_hierarchy_version as org14_18_0_,......this_.type as type18_0_, this_.work_space_id as work19_18_0_, this_.zoom as zoom18_0_ from org_unit this_ where this_.name=? and this_.work_space_id=?

我不确定为什么 Grails 会忽略主键并尝试根据辅助键检索实体。

任何想法表示赞赏。

谢谢, 基肖尔

【问题讨论】:

    标签: grails


    【解决方案1】:

    Grails 不会尝试检索这个。这是唯一约束 - 在保存之前检查“每个工作区的名称”。

    看起来 save() 毕竟失败了。它真的会默默地失败吗?那么mergedOu.hasErrors()呢?

    【讨论】:

    • 感谢您的回复。它确实会默默地失败。 mergeOu.hasErrors() 返回 false。
    • 我正在查看 p6spy 日志,提交似乎正在发生而没有发布更新语句。我不知道为什么。
    • 这可能是 Grails merge() 功能的问题。通常的范例是,如果你想更新一个实体,那么,在控制器中,你有一个作为参数传入的属性映射。根据 params.id 从数据库中检索对象,然后将属性从 params 复制到对象中并保存。如果尝试在我的服务类中模仿它,它似乎工作正常。而且我似乎找不到任何使用 merge() 的 Grails 示例。顺便说一句,我使用的是 Grails 1.3.3。如果其他人使用相同的 Grails 版本并且有合并工作,我想知道。非常感谢!
    • mergedOu.validate() && mergedOu.hasErrors() 怎么样?实际上,Grails 使用了其他方法,例如 def ou = OrgUnit.get(id); ou.properties = params。也许在您的情况下可以使用properties = something 解决方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2011-10-05
    相关资源
    最近更新 更多