【问题标题】:GORM : Relationship table not updated in many-to-many mappingGORM:关系表未在多对多映射中更新
【发布时间】:2015-03-24 14:36:40
【问题描述】:

我有两个通过多对多关系相关的域类(简化)。

一个团队可以有多个玩家,一个玩家可以属于多个团队。

当我调用团队控制器'save'操作时:

  1. 一名玩家被保存在桌子上。 (如预期)
  2. 一个团队被保存在表中。 (如预期)
  3. 当我打印 team.players 和 player.teams 时,我看到了正确的输出(见下面的代码)
  4. 关系表 (TEAM_PLAYERS) 中没有保存任何内容。为什么会这样?我需要自己在连接表中输入吗?如果此表没有更新,我如何看到第 3 点的正确输出?

Team.groovy 是:

class Team {

   static hasMany = [players : Player]
   String name;
   String size;
}

Player.groovy 是:

class Player {

   static hasMany = [teams : Team]
   static belongsTo = Team

   String fullName;
   String age;
}

TeamController.groovy 是:

class TeamController {

   def save() {
      def player = new Player(fullName : "John Doe", age : "21").save()
      def team = new Team(name : "LocalXI", size : "1").addToPlayers(player).save();
      println "The players in the team are : " + team.players
      println "The teams this player belongs to are : " + player.teams
   }
}

输出(当我调用“保存”操作时):

The players in the team are : [John Doe]
The teams this player belongs to are : [LocalXI]

我是 Grails 和 Groovy 的新手,我花了很多时间试图弄清楚这一点。

【问题讨论】:

标签: grails many-to-many grails-orm


【解决方案1】:

它应该工作。考虑到 save 方法默认是事务性的,在方法完成之前它实际上不会持久化数据。在事务中,一切看起来都是正确的,这就是 println 输出正确的原因。

如果您通过集成测试测试此控制器,您的数据将不会被持久化,因为每次测试都会自动回滚事务。

如果您通过浏览器手动测试,请确保您没有在当前运行时环境中使用内存数据库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多