How to handle an empty list in Grails / GORM?

I am trying to get a one-to-many relationship working with grails / gorm. I do not understand how to handle an empty list.

Here is my domain class:

class Parent { List children static hasMany = [children: Children] } 

Here is my test:

 void testEmptyChildren() { def parent = new Parent() assert 0, parent.children.size() } 

This does not work with "java.lang.NullPointerException: cannot call the size () method on a null object"

What should I do to process an empty list?

+4
source share
2 answers

In your test, parent.children will always be null (children will not be initialized until you add the first one). Therefore, you can change your test to:

 assertNull parent.children 

Children will be initialized when the parent is retained (regardless of whether children are added) or when children are added. If you want it to always be initialized, you can do it manually in the parent when you define children:

 List<Children> children = new ArrayList<Children>() 
+7
source

I get similar results (perhaps the children remain empty). note that you should use an integration test for gorm content.

you can handle the empty list as follows:

 parent.children?.each { println it} parent.addToChildren(new Children(/* whatever you need */)) parent.children?.each { println it} 
0
source

All Articles