我是一支有4名球员的球队。每个玩家的位置都很重要,所以我认为我使用地图为我的玩家提供了一个很好的方式,其中包括:pos1
,pos2
,pos3
,pos4
class Team {
Map players = [pos1:null, pos2:null, pos3:null, pos4:null]
static hasMany = [players:Player]
League league
static belongsTo = [club:Club]
static constraints = {
league nullable:true
players nullable:true
}
}
和我的玩家:
class Player{
static belongsTo = [club:Club, team:Team]
String firstname
String lastname
Team team
static constraints = {
team nullable:true
firstname nullable:true
lastname nullable:true
}
public String fullname() {
return firstname + " " + lastname + " - " + team?.id ?: "R"
}
}
我使用addToPlayers()
方法让播放器自动更新,但是当我尝试以下操作时出现错误:
def player = new Player(firstname:"Peter", lastname:"Pan")
def team = new Team()
team.addToPlayers([pos1:player])
Stacktrace说:
Groovy.lang.MissingMethodException: No signature of method:
org.hibernate.collection.PersistentMap.add() is applicable for argument types:
(at.panda.Player) values: [at.panda.Player : null]
Possible solutions: any(), any(groovy.lang.Closure), any(groovy.lang.Closure), wait(),
wait(long), get(java.lang.Object)
at at.panda.PlayerController$_closure4.doCall(PlayerController.groovy:39)
at at.panda.PlayerController$_closure4.doCall(PlayerController.groovy)
at java.lang.Thread.run(Thread.java:662)
这花了我很多时间,我希望有人可以帮助我。我不需要坚持" Map"如果你有更好的解决方案。
答案 0 :(得分:3)
如果域对象中有Map属性,则键和值必须都是字符串:Grails Manual: Object Relational Mapping。
但是你为什么要为你的球员使用地图?如果您只有四名球员,只需将您的球队定义为:
class Team {
Player pos1
Player pos2
Player pos3
Player pos4
...
}
答案 1 :(得分:0)
就个人而言,我会像这样建立您的域名:
class Team {
//Map players = [pos1:null, pos2:null, pos3:null, pos4:null]
static hasMany = [players:Player]
// The reference to league is now specified below in belongsTo
//League league
static belongsTo = [club:Club,league:League]
static constraints = {
league nullable:true
// must have 4 players
players(size: 4..4)
}
}
class Player{
// Remove the reference to club as this can be retrieved through the Team
static belongsTo = [/*club:Club,*/ team:Team]
String firstname
String lastname
Integer position
// Remove this duplicate reference to team
//Team team
static constraints = {
team nullable:true
firstname nullable:true
lastname nullable:true
// This should ensure that you can't create 2 players with the same position
// in the same team
position(unique:'team')
}
}
此模型可让您更轻松地按位置排列所有玩家,如果您决定要更改玩家数量,您需要做的就是更改约束players(size: 4..4)
我会考虑向Team添加addPlayer(Player player)
方法,负责正确设置位置属性。
如果尚未测试上述任何代码,请小心处理。