我有以下域类:
class Team{
static hasMany = [localMatches: Match, visitingMatches: Match]
static mappedBy = [localMatches: 'localTeam', visitingMatches: 'visitingTeam']
List<Match> localMatches = new ArrayList<Match>()
List<Match> visitingMatches = new ArrayList<Match>()
}
class Match{
Team localTeam
Team visitingTeam
}
当我运行以下内容时:
Match match = new Match(localTeam: aLocalTeam, visitingTeam: aVisitingTeam)
match.save(flush: true, failOnError: true)
我得到异常“引起:org.h2.jdbc.JdbcSQLException:列不允许NULL”LOCAL_TEAM_ID“; SQL语句:”
所以我需要在保存匹配之前在每个团队中设置匹配以避免异常:
Match match = new Match(localTeam: aLocalTeam, visitingTeam: aVisitingTeam)
aLocalTeam.localMatches.add(match)
aVisitingTeam.localMatches.add(match)
match.save(flush: true, failOnError: true)
有没有办法映射这些类,所以我不需要在保存之前将匹配添加到每个团队?
答案 0 :(得分:2)
hasMany
块定义Match
有多个localMatches
,但接下来重新定义localMatches
作为与单个Match
的关系。我认为你的意思是:
class Team {
static hasMany = [localMatches: Match, visitingMatches: Match]
static mappedBy = [localMatches: 'localTeam', visitingMatches: 'visitingTeam']
}
class Match {
Team localTeam
Team visitingTeam
}
以这种方式映射,Team
将有两个Matches
集合,每个Match
将有一个local
和visiting Team
。