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

前端 未结 2 874
春和景丽
春和景丽 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:22

    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.

    0 讨论(0)
  • 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 = [])

    0 讨论(0)
提交回复
热议问题