【问题标题】:GORM Mapping two attributes of same Class with hasManyGORM 用 hasMany 映射同一个类的两个属性
【发布时间】:2012-06-27 03:52:05
【问题描述】:

我有以下:

class Match{ 
    Team localTeam
    Team visitingTeam
}

class Team{
    static hasMany = [matches: Match]
}

抛出: 加载插件管理器时出错:类 [class myapp.Team] 中的属性 [matches] 是双向的一对多,反面有两个可能的属性。要么命名关系 [team] 另一侧的属性之一,要么使用“mappedBy”静态定义关系映射的属性。示例:静态 mappedBy = [matches:'myprop']

所以,我使用'mappedBy':

class Team{
    static hasMany = [matches: Match]
    static mappedBy = [matches: localTeam, matches: visitingTeam]
}

但是,通过这样做,当我从 db 获得球队时,matches Set 仅包含球队是客队的比赛,这意味着它只将比赛映射到访问队。

如果我编写以下代码:

class Team{
    static hasMany = [matches: Match]
    static mappedBy = [matches: localTeam]
}

它只映射本地团队的匹配。

有没有办法将两场比赛(当球队是本地的,当它是访客时)映射到球队?

【问题讨论】:

  • 有什么解决办法吗?

标签: grails mapping grails-orm


【解决方案1】:

请先阅读有关 GORM 性能问题的文章:https://mrpaulwoods.wordpress.com/2011/02/07/implementing-burt-beckwiths-gorm-performance-no-collections

这可能就是你要找的东西:

class Team {
   String name
   String description

   static constraints = {
    name blank: false, nullable: false
    description blank: true, nullable: true
   }

   static mapping = {
      description type: 'text'
   }

   Set<Match> getHomeMatches() {
    Match.findAllByHomeTeam(this).collect { it.homeTeam } as Set
   }

   Set<Match> getMatches() {
    Match.findAllByTeam(this).collect { it.team } as Set
   }
}


class Match {

   Team homeTeam
   Team team

   static constraints = {
    homeTeam nullable: false
    team nullable: false
   }

   static mapping = {
    id composite: ['homeTeam', 'team']
   }   
} 

【讨论】:

  • 这是一个非常有趣的方法,但不是我想要的
【解决方案2】:

试试这个

class Team {
    static hasMany = [localTeamMatches: Match, visitingMatches: Match]
    static mappedBy = [localTeamMatches: "localTeam", visitingMatches: "visitingTeam"]
}

【讨论】:

  • 主要问题是我只想维护一个集合“匹配”,而不是两个
猜你喜欢
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
相关资源
最近更新 更多