Skip to content

Instantly share code, notes, and snippets.

@ggayan
Created February 13, 2010 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggayan/303737 to your computer and use it in GitHub Desktop.
Save ggayan/303737 to your computer and use it in GitHub Desktop.
Some guides to model m:n relationships in grails using lists(for sorting) or not
//Domain classes...
class Team {
String name
static hasMany = [memberships:Membership]
static constraints = {}
}
class Player {
String name
static hasMany = [memberships:Membership]
static constraints = {}
}
//link class with attributes
class Membership {
boolean active = true
static belongsTo = [team:Team, player:Player]
static constraints = {}
}
//Domain classes with lists to define some order on relationships
class Team {
...
List squadMemberships
static hasMany = [teamMemberships:Membership]
...
}
class Player {
...
List playerMemberships
static hasMany = [playerMemberships:Membership]
...
}
/*
* Mapping name for Membership in Player and Team classes
* must be different to avoid org.hibernate.MappingException
*/
//to persist:
def player = new Player(name:"Fernando Torres")
player.save()
def team = new Team(name:"Liverpool FC")
team.save()
def membership = new Membership(player:player, team:team, active:true)
player.addToMemberships(membership)
team.addToMemberships(membership)
//credits to http://codedumpblog.blogspot.com/2010/02/grails-many-to-many-with-lists.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment