Can someone help with a cascading delete problem? Code is below.
I have a Team that contains a set of Games. A Game refers to a home and an away team. If i delete a Team, I want all its games to be deleted. This means it should remove the games from the other Team's list of games too.
Right now, when i delete a team, all of its games are left in the DB. And then I get errors when I load lists of games since the home/away field refers to a team that doesn't exist anymore.
Is there something else I need to configure in my cascade besides CascadeType.ALL? Would delete-orphan even work, since the Game is still referred to by another Team?
Thanks,
Tauren
Code:
/*
// This code deletes the Team entity, but not the set of Games in the Team
Team team = getSession().load(Team.class, 5);
getSession().delete(team);
// How do I make it cascade to delete the Games as well? Note that a Game is referenced by
// two Teams (home and away). If one Team is deleted, then there shouldn't be a game
// anymore and that game should be removed from the other Team's list of games. Why
// doesn't CascadeType.ALL do this?
*/
@Entity
@Table(name="teams")
public class Team extends NamedEntity {
private Set<Game> games = new HashSet<Game>();
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(
name="teams_games",
joinColumns = @JoinColumn( name="team"),
inverseJoinColumns = @JoinColumn( name="game")
)
public Set<Game> getGames() {
return games;
}
public void setGames(Set<Game> games) {
this.games = games;
}
}
@Entity
@Table(name="games")
public class Game extends NamedEntity {
private Team home;
private Team away;
@ManyToOne
@JoinColumn(name = "home")
public Team getHome() {
return home;
}
public void setHome(Team home) {
this.home = home;
}
@ManyToOne
@JoinColumn(name = "away")
public Team getAway() {
return away;
}
public void setAway(Team away) {
this.away = away;
}
}