本文简单介绍Grails中使用Gorm的多对多映射,本文使用的例子延续前面的文章(一)中的例子,可以更好的对比一对多、多对多映射的异同。 (1)创建一个grails的应用:grails create-app GormDemo2 (2)创建三个domain grails create-domain-class Member grails create-domain-class Team grails create-domain-class Membership (3)修改Member.groovy文件 class Member { String name static hasMany = static mappedBy =
def teams() { return memberships.collect{it.team} }
List addToTeams(Team team) { Membership.link(this, team) return teams() }
List removeFromTeams(Team team) { Membership.unlink(this, team) return teams() } } (4)修改Team.groovy文件 class Team { String name Member member static belongsTo = Member static hasMany =
List members() { return memberships.collect{it.member} }
List addToMembers(Member member) { Membership.link(member, this) return members() }
List removeFromMembers(Member member) { Membership.unlink(member, this) return memberes() } } 在多对多的映射中,只需在两端都指定hasMany即可,不过要注意的是,必须要在某一端指定belongsTo (5)修改Membership.groovy 在hibernate的多对多映射中需要建一个中间的表来关联两个表,因此需要创建这个Membership类 class Membership { Member member Team team
static Membership link(member, team) { def m = Membership.findByMemberAndTeam(member, team) if (!m) { m = new Membership() member?.addToMemberships(m) team?.addToMemberships(m) m.save() } return m }
static void unlink(member, team) { def m = Membership.findByMemberAndTeam(member, team) if (m) { member?.removeFromMemberships(m) team?.removeFromMemberships(m) m.delete() } } } (6)让grails自己生成controller和views grails generate-all Member grails generate-all Team grails generate-all Membership (7) 启动该web工程:grails run-app 在浏览器下输入:http://localhost:8080/GormDemo2
附件:
|