问题
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?
回答1:
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.
Ref Collections in GORM
来源:https://stackoverflow.com/questions/29213809/why-is-grails-hasmany-list-size-wrong