返回列表 发帖

[原创] [原创]Grails使用GORM(二)

本文简单介绍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自己生成controllerviews
grails generate-all Member
grails generate-all Team
grails generate-all Membership
(7) 启动该web工程:grails run-app
在浏览器下输入:http://localhost:8080/GormDemo2


附件:
天行健,君子以自强不息
地势坤,君子以厚德载物
   黑色海岸线欢迎您

返回列表 回复 发帖