为什么Grails有很多列表大小错误? [英] Why is Grails hasMany List size wrong?
问题描述
我有一个具有hasMany关系的域对象Parent,实现为List。
class父类{
列出子元素
static hasMany = [children:Child,otherHasMany:SomeOtherChildClass]
static mapping = {
children lazy:false
}
}
def parent = Parent.get(someId)// parent作为查询的结果返回
def numChildren = parent.children.size()
我在子列表中获取了很多散布在正确子元素中的空值。
parent.children.each {
println it
}
给出:
子元素1
NULL
子元素2
NULL
子元素3
子元素4
... //看似随机在正确值之间插入NULL的顺序,但在一行中从未出现过2个NULL
在我的的情况下, size()
调用返回71个Children,但只有51个Children应该在Parent中。
当我执行一个SQL查询时,我得到了正确数量的孩子:
来自CHILDREN的SELECT count(*)where parent_id = someId
51
打开SQL日志记录并检查查看Hibernate是执行,我得到了同样的正确答案(51)。
我在做什么错误吗?
创建域时,就像您创建了
$ b一样$ b
class父类{
列出子元素
static hasMany = [children:Child]
}
然后为了完成这个工作,grails将 children_idx
列添加到 Child
表。这个列中的值很重要,因为grails使用它来创建列表(按顺序放置实例)。第一条记录将其值设置为 0
,下一个 1
等等。 这可能是问题所在。
为避免破坏序列,请确保在删除关联对象时从关联对象中删除关联对象。
参考 GORM集合
I have a domain object Parent that has a hasMany relationship implemented as a List. I am getting an incorrect size of List returned and I don't know why:
class Parent {
List children
static hasMany = [children : Child, otherHasMany : SomeOtherChildClass]
static mapping = {
children lazy: false
}
}
def parent = Parent.get(someId) // parent is returned as a result of a query
def numChildren = parent.children.size()
I am getting a lot of null values interspersed amongst the correct Children within the children List.
i.e.
parent.children.each {
println it
}
gives:
Child 1
NULL
Child2
NULL
Child3
Child4
... // seemingly random order of NULLs interspersed between correct values, but there never appear to be 2 NULLs in a row
In my case, the size()
call returns 71 Children, yet there are only 51 Children that should be in the Parent.
When I execute an SQL query I get the correct number of Children:
SELECT count(*) from CHILDREN where parent_id = someId
51
When I turn on SQL logging and check to see the query that Hibernate is executing, I get the same correct answer (51).
What am I doing wrong please?
When a domain is created like you have created
class Parent {
List children
static hasMany = [children : Child]
}
then to make this work, grails add the children_idx
column to the Child
table. The values in this column are important because grails use this for making list (placing instance in order). The first record will have its value set to 0
, the next 1
, and so forth. And if this sequence is broken, then you got null in the list.
This may be the issue.
To avoid breaking the sequence, make sure you remove the associated object from its owner when deleting the associated object.
这篇关于为什么Grails有很多列表大小错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!