Zakk Ge
Zakk Ge

Reputation: 3

How can this behaviour using a Hibernate query be explained? Is it due to Hibernate lazyness?

This morning, I ran into a behaviour i can not really explain : when trying to save (or retrieve if it already exists) some objects with the help of GORM, i was surprised by a NullPointerException when a object (with name "name3") is simply retrieved from the db and stored in a List and read as null afterwards. What surprised me is when i stored this object in a def variable (or whatever is not a collection, i guess), the exception disappear.

Here is a sample code (the database is empty at the beginning, by the way)

// A simple domain class : 
class MyDomainClass {
    String name
}


//In the PluginClass where i initialize some pieces of data : 
def doWithApplicationContext = { ctx ->

    MyDomainClass.withNewSession {

        def myDomainObjectsNames = ["name1","name2"]
        def myDomainObjectsList = []
        myDomainObjectsNames.each { name ->
            def myDomainObject = MyDomainClass.findByName(name) ?: new MyDomainClass(name: name).save(failOnError: true)
            myDomainObjectsList.add(myDomainObject)
        }
        myDomainObjectsList.each { println("object : " + it.toString())}

        myDomainObjectsNames = ["name3","name2"]
        myDomainObjectsList = []
        myDomainObjectsNames.each { name ->
            myDomainObjectsList << MyDomainClass.findByName(name) ?: new MyDomainClass(name: name).save(failOnError: true)
        }
        myDomainObjectsList.each { println("object : " + it.toString())}
    }
}

Code output :

object : mypackage.MyDomainClass : 1
object : mypackage.MyDomainClass : 2
object : null // Can't explain
object : mypackage.MyDomainClass : 2

Could it be due to Hibernate lazyness? Or Groovy dynamic typing ? I'm not sure. Thanks !

Upvotes: 0

Views: 59

Answers (1)

cfrick
cfrick

Reputation: 37008

it is not about the local variable, but the precendence of << vs ?:. Your second loop there adds the result of the findBy to the list first.

def list = []
list << null ?: 666
assert list.first()==null

Upvotes: 1

Related Questions