All,
I am using Hibernate JPA and am encountering difficulties persisting a one to many relationship.
Assume I have the following entities:
Team
Code:
@Entity
@Table(name="team")
public class Team implements Serializable {
// ... attributes ...
@OneToMany(mappedBy="team", cascade=CascadeType.ALL)
private Set<Player> players = new HashSet<Player>();
public void addPlayer(Player player) {
players.add(player);
}
// ... methods - using POJO getters / setters ...
}
PlayerCode:
@Entity
@Table(name="player")
public class Player implements Serializable {
// ... attributes ...
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="team_id")
private Team team;
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
// ... methods - using POJO getters / setters ...
}
In my code, I create a Team and add a Player to it as follows:
Code:
Player player = new Player();
player.setName("My player");
Team team = new Team();
team.setName("My team");
// NOTE: Foreign key *not* null if the following line uncommented
//player.setTeam(team);
team.addPlayer(player);
// Uses JPA persist method
teamDAO.saveTeam(team);
In the player table, the team_id column is being set to null and therefore there is no reference back to their team. Of course, if I uncomment the player.setTeam(team) method call, the team_id column is correctly set in the player table (as I would expect).
I thought Hibernate would automatically set the team_id column for each Player entity as they're added to the Set? Am I missing something?
Thanks!
Damian