Japanese GORM - Managing Relationshi...

Last updated by admin 4 years ago

???????? Managing Relationships

Since 0.3, Grails provides quite a few methods to easy relationship management. Firstly if you have a one-to-many relationship such as the Author-Book relationship defined below:

class Author {
String name
static hasMany = [books:Book]
}
class Book {
String title
Author author
static belongsTo = Author
}

You can use the dynamic addBook method on author to ease relationship management:

def a = new Author(name:"Stephen King")
.addBook(new Book(title:"IT"))
.addBook(new Book(title:"The Stand"))
.save()

The {{addBook}} method is available at runtime and uses the class name of the {{Book}} to automatically establish the relationship. If it is bidirectional it will also make sure that the {{author}} property of the {{Book}} instance is set.

If you have more than one one-to-many relationship defined for the same class:

class Author {
String name
static hasMany = [fiction:Book, non-fiction:Book]
}
You can use the {{add}} method which takes a {{to}} argument which defines which collection to add the book to:

def a = new Author(name:"Stephen King")
.add(to:"fiction",
new Book(title:"IT"))
.add(to:"non-fiction",
new Book(title:"On Writing: A Memoir of the Craft"))
.save()