GrailsInAction / graina2

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

MEAP v9, chapter 5, code from github : profile for admin is invalid #29

Closed marcpa00 closed 11 years ago

marcpa00 commented 11 years ago

Code for ch5 downloaded from github have this in grails-app/conf/BootStrap.groovy:

private createAdminUserIfRequired() {
    if (!User.findByLoginId("admin")) {
        println "Fresh Database. Creating ADMIN user."

        def profile = new Profile(email: "admin@yourhost.com")
        new User(loginId: "admin", password: "secret", profile: profile).save()
    }
    else {
        println "Existing admin user, skipping creation"
    }
}

1) fullName is required in Profile class 2) save() fails silently (because profile contains errors, fullName cannot be null)

The effect of this is that it fails later on in createSampleData() at the time of the first save() with flush:true.

| Error 2013-07-10 15:55:37,978 [localhost-startStop-1] ERROR hibernate.AssertionFailure  - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
Message: null id in com.grailsinaction.Profile entry (don't flush the Session after an exception occurs)

At that point, it is not very easy to see what went wrong as the line where the failure occurs is far from the line having the root cause.

Note that adding failOnError: true in the save() call on admin user won't trigger the exception; only when hibernate actually tries to commit the session to database will it throw the error.

Adding fullName: "Administrator" to creation of profile fixes the issue. I would suggest also using "admin@nowhere.net" for the email to be consistent with rest of data created in bootstrap and to add failOnError:true, flush:true to the save() call.

pledbrook commented 11 years ago

As mentioned in the pull request, I pushed a separate fix just now before seeing the pull request.