GrailsInAction / graina2

Source code for the 2nd edition of Grails in Action
90 stars 92 forks source link

5.2.2 No ClassCastException #21

Closed philfriesen closed 10 years ago

philfriesen commented 11 years ago

The book says that when the following code is run as a script in the console:

Post.where { user.loginId == 12 }.list()

we should see a ClassCastException because loginId is a String property and 12 is not a String.

Actually, the integer is automatically converted to a String so no ClassCastException is thrown. I verified this by adding the following code to Bootstrap.groovy:

        def twelve = new User(loginId: "121212",
                password: "aaaaaa",
                profile: new Profile(fullName: "Twelfth man", email: "12@nowhere.net"),
                dateCreated: now - 2).save(failOnError: true)

        twelve.addToPosts(content: "Very first post")
        twelve.addToPosts(content: "Second post")
        twelve.save(failOnError: true)

and changing the console script to:

import com.grailsinaction.*
println Post.list().user.loginId
println Post.where { user.loginId == 121212 }.list()
println "There are ${Post.count()} posts in the database"

The script results were:

groovy> import com.grailsinaction.* 
groovy> println Post.list().user.loginId 
groovy> println Post.where { user.loginId == 121212 }.list() 
groovy> println "There are ${Post.count()} posts in the database" 

[121212, 121212, dillon, sara, phil, sara, phil, sara, phil, phil, sara, sara, sara, phil, phil]
[com.grailsinaction.Post : 8, com.grailsinaction.Post : 9]
There are 15 posts in the database
pledbrook commented 11 years ago

Gah, I thought I'd checked that before putting it in. Thanks for catching that. I need to go over chapter 5 again anyway, so I'll revisit this and perhaps use a different example.

pledbrook commented 10 years ago

I changed to using dateCreated for the example. Interestingly, I can no longer see a ClassCastException - I get a ConversionFailedException instead. I have a note to check the behaviour for whatever version of Grails we eventually plump for in the book. At this rate, could be Grails 2.4, but more likely 2.3.