Tuesday, July 12, 2011

Many-to-many relationship mapping with GORM/Grails

Many-to-many relationship mapping with GORM/Grails

GORM (Grails’s abstraction of Hibernate) lets you define a many-to-many relationship like this:

class User {
String name
static hasMany = [groups: Group]
}

class Group {
String name
static hasMany = [members : User]
static belongsTo = User
}

This relationship can be accessed through some helpful dynamic methods that Grails provides:

new User(name: "foo").addToGroups(name: "bar").save()
// creates a new user AND group, saves both of them
// and the relationship

def user = new User(name: "foo").save()
new Group(name: "bar").save().addToMembers(user)
// as above, but addToMembers will not cascade the relationship
// to the user

No comments:

Post a Comment