Grails映射以在保存实例时解决异常

时间:2012-12-12 01:43:33

标签: grails mapping hibernate-mapping

我有以下域类:

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)

有没有办法映射这些类,所以我不需要在保存之前将匹配添加到每个团队?

1 个答案:

答案 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将有一个localvisiting Team