我们有一个像这样的 Domain 类:
class Attribute {
List attributeParameters = []
static hasMany = [attributeParameters: AttributeParameter]
}
AttributeParameter
属于Attribute
。这里还定义了其他几种关系,并且有一个实例,我们需要删除多个属性中的多个属性参数。所以我们正在这样做:
def parameters = AttributeParameter.findAllBySomeOtherCriteria(foo)
parameters*.delete()
这是可行的,但是,attribute_parameter 中有一列名为 attribute_parameters_idx
的顺序不正确。此列存在是因为我们已将集合定义为列表。如果我们执行 attribute.removeFromAttributeParameters(ap)
,Grails 会自动调整此列。但由于我们没有以这种方式删除数据,因此它们会乱序。
当发生这种情况时,我们在从属性循环遍历集合时会得到空值。这不是缓存问题或刷新父问题。当我们这样做时会发生什么:
attribute.attributeParameters.each { }
内部正在根据 _idx 值在迭代中添加额外的行。由于其中一行(或多行)丢失,Grails 将在 Collection 中添加一个空行。您在调试时看不到这一点,但您可以在迭代发生时观察它。
最后我的问题是:
- 有没有办法告诉 Grails 更新特定集合的 _idx 值,如果没有
- 有没有办法获取这个 _idx 列并通过 Gorm 手动修改其值
最佳答案
我认为这取决于 Hibernate 如何处理集合,尤其是像 List 这样的索引集合。如果不使用 addTo
和 removeFrom
Hibernate 不知道它需要更新索引。
作为一种解决方法,我可以想到这样的事情:
在 AttributeParameter
类上添加 afterDelete
事件。在其中,您需要类似的内容:
def afterDelete() {
def sql = new Sql(dataSource)
sql.execute("update attribute_attribute_parameter set attribute_parameter_idx = " +
"attribute_parameter_idx - 1 where attribute_parameter_idx > " +
"(select attribute_parameter_idx from attribute_attribute_parameter where " +
"attribute_parameter_id = $id and attribute_id = $attribute.id) " +
"and attribute_id = $attribute.id")
}
PS。尽管它是私有(private)的,但我认为您可以使用 getIndexColumnName()
动态获取索引列名称。
关于list - Grails 在删除时调整 _idx 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13827542/