Created
February 13, 2010 23:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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