Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy grails throwing null pointer exception while accessing hasMany relationship first time?
    primarykey
    data
    text
    <p>I have a strange problem.<br> I have two domain classes <code>User</code> and <code>Post</code> with fields: </p> <pre><code>class User { String name static hasMany = [posts: Post] static constraints = { } } </code></pre> <p>and</p> <pre><code>class Post { String content long date = System.getTimeInMillis() static constraints = { } static belongsTo = [user: User] static mapping = { version: 'false' } } </code></pre> <p>and controller code is: </p> <pre><code>class UserController { def addUser = { def user if (User.count() == 0) { user = new User() user.name = "Manish Zedwal" user.save(flush: true) } else { user = User.get(1) } println "Posts count: " + user.posts.size() render "post count: " + user.posts.size() } } </code></pre> <p>For the first time while accessing url <code>http://localhost:8080/test/user/addUser</code>, it throws null pointer exception, but after this works fine.<br> This is the exception I am getting</p> <pre><code>2011-08-04 15:41:25,847 [http-8080-1] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /test/user/addUser Stacktrace follows: java.lang.NullPointerException: Cannot invoke method size() on null object at test.UserController$_closure2.doCall(UserController.groovy:18) at test.UserController$_closure2.doCall(UserController.groovy) at java.lang.Thread.run(Thread.java:636) </code></pre> <p>and for second time, it prints and renders fine like charm</p> <pre><code>Posts count: 0 </code></pre> <p>In user domain class, coz of <code>hasMany</code> relationship for <code>posts</code>, <code>posts</code> is a list of <code>Post</code> objects then there shouldn't be null pointer exception on getting the size of empty list, rather it should be zero.</p> <p>Any help appreciated </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload