Forcing Grails GORM Relationship Collection Types

Thursday, July 02, 2009 by Brandon Comments

When you define a has-many relationship on a domain model in Grails, it automatically creates the collection for you and the getters/setters to make it a property. By default, doing something like this:

class Author implements Serializable {
    String name

    static def hasMany = [books: Book]
}

creates a java.util.Set called books in your model that you can access using author.books.  A problem arises when you don’t want that collection to be a plain old set (P.O.S.)  What if you want it to be a SortedSet or possibly a list so you can access elements like author.books[1]?  It’s easy to force GORM to create that collection as something other than a Set: just create a property with the same name of the type of collection class you want.  So our previous example becomes:

class Author implements Serializable {
    String name

    List books
    static def hasMany = [books: Book]
}

Now author.books is a List instead of a Set.  It’s as simple as that.

blog comments powered by Disqus