Why is Grails hasMany List size wrong?

寵の児 提交于 2020-01-07 05:04:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!