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

前端 未结 2 882
春和景丽
春和景丽 2021-02-18 15:48

I have a strange problem.
I have two domain classes User and Post with fields:

class User {
  String name
  static hasMany = [pos         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-18 16:37

    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 = [])

提交回复
热议问题