我有以下非常简单的一对多关系:
球队有一组球员:
@Entity(name = "TEAM")
@Access(AccessType.PROPERTY)
public class Team{
private Integer id;
private String name;
private Set<Player> players ;
@Id
@Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "team_name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = {CascadeType.ALL},orphanRemoval=true)
@JoinColumn(name = "TEAM_ID")
public Set<Player> getPlayers() {
return players;
}
public void setPlayers(Set<Player> players) {
this.players = players;
}
}
每个玩家都有一个唯一的 id 和 name。
@Entity(name = "PLAYER")
@Access(AccessType.PROPERTY)
public class Player implements Serializable{
private int id;
private String name;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "player_name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
return id == ((Player)obj).id;
}
@Override
public int hashCode() {
return id;
}
}
我运行一个非常简单的代码:
Team team = createTeam(3) // creates team with 3 players ids={1,2,3}
session.saveOrUpdate(team);
...
private Team createTeam(int players) {
Team team = new Team();
team.setName("Bears");
team.setId(1);
for(int i=1 ; i<=players; ++ i){
Player player = new Player();
player.setId(i);
player.setName("Player"+i);
team.addPlayer(player);
}
return team;
}
我得到以下预期:
- 休眠:从 TEAM team_ 中选择 team_.id, team_.team_name 作为 team2_0_ where team_.id=?
- 休眠:从 PLAYER player_ where player_.id=? 中选择 player_.id, player_.player_name 作为 player2_1_
- 休眠:从 PLAYER player_ where player_.id=? 中选择 player_.id, player_.player_name 作为 player2_1_
- 休眠:从 PLAYER player_ where player_.id=? 中选择 player_.id, player_.player_name 作为 player2_1_
- Hibernate:插入 TEAM (team_name, id) 值 (?, ?)
- Hibernate:插入 PLAYER (player_name, id) 值 (?, ?)
- Hibernate:插入 PLAYER (player_name, id) 值 (?, ?)
- Hibernate:插入 PLAYER (player_name, id) 值 (?, ?)
- 休眠:更新 PLAYER 设置 TEAM_ID=? 哪里id=?休眠:更新 PLAYER 设置 TEAM_ID=? 哪里id=?休眠:更新 PLAYER 设置 TEAM_ID=? 哪里id=?
然后我做:
Team team = createTeam(2) // creates team with 2 player ids={1,2}
session.saveOrUpdate(team);
并期望删除孤儿玩家,但我得到:
- 休眠:从 TEAM team_ 中选择 team_.id, team_.team_name 作为 team2_0_ where team_.id=?
- 休眠:从 PLAYER player_ where player_.id=? 中选择 player_.id, player_.player_name 作为 player2_1_
- 休眠:从 PLAYER player_ where player_.id=? 中选择 player_.id, player_.player_name 作为 player2_1_
- 休眠:更新 PLAYER 设置 TEAM_ID=null where TEAM_ID=?
- 休眠:更新 PLAYER 设置 TEAM_ID=? 哪里id=?
- 休眠:更新 PLAYER 设置 TEAM_ID=? 哪里id=?
这使孤儿播放器(id = 3)断开连接但没有被删除......有什么想法我做错了吗?