Why grails throwing null pointer exception while accessing hasMany relationship first time?

不羁岁月 提交于 2019-12-04 00:00:28

When you map a collection like that, the hasMany declaration adds a field of type Set with the specified name (in this case posts) to your class. It doesn't initialize the set though, so it's initially null. When you call addToPosts it checks if it's null and creates a new empty Set if necessary, and adds the Post to the collection. But if you don't call addToPosts or explicitly initialize the set, it will be null.

When you load a User from the database, Hibernate will populate all the fields, and the collection is included in that. It creates a new Set (a modification-aware PersistentSet) that's empty, and adds instances to it if there are any. Calling save() doesn't reload the instance from the database though, so the null set will still be null.

To get the class to behave the same way when it's new and when it's persistent, you can add a field to your class Like Rob showed in his answer, initialized to an empty set (Set posts = [])

You can prevent this by explicitly declaring your collection property (with a value) alongside your mapping:

class User {
    String name
    Set posts = []
    static hasMany = [posts: Post]
}

You can define the collection type you need. The default is Set, but if you need to maintain order, you might consider List or SortedSet.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!