Reputation: 8698
I have the following domain classes:
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
}
When I run the following:
Match match = new Match(localTeam: aLocalTeam, visitingTeam: aVisitingTeam)
match.save(flush: true, failOnError: true)
I get the exception "Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "LOCAL_TEAM_ID"; SQL statement:"
So I need to set the match in each team before saving the match to avoid the exception:
Match match = new Match(localTeam: aLocalTeam, visitingTeam: aVisitingTeam)
aLocalTeam.localMatches.add(match)
aVisitingTeam.localMatches.add(match)
match.save(flush: true, failOnError: true)
Is there any way of mapping the classes so I wouldn't need to do add the match to each team before saving?
Upvotes: 0
Views: 142
Reputation: 101
The hasMany
block defines that a Match
has many localMatches
, but then below redefines localMatches
as a relationship to a single Match
. What I believe you actually mean is:
class Team {
static hasMany = [localMatches: Match, visitingMatches: Match]
static mappedBy = [localMatches: 'localTeam', visitingMatches: 'visitingTeam']
}
class Match {
Team localTeam
Team visitingTeam
}
Mapped this way, Team
will have two collections of Matches
and each Match
will have a local
and visiting Team
.
Upvotes: 2