我有以下相对简单的一对多关系:
团队拥有一组球员:
@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;
}
我得到了以下预期的结果:
- Hibernate:从TEAM team_中选择team_.id,team_.team_name作为team2_0_ where team_.id=?
- Hibernate:从PLAYER player_中选择player_.id,player_.player_name作为player2_1_ where player_.id=?
- Hibernate:从PLAYER player_中选择player_.id,player_.player_name作为player2_1_ where player_.id=?
- Hibernate:从PLAYER player_中选择player_.id,player_.player_name作为player2_1_ where player_.id=?
- Hibernate:将(team_name, id)值(?, ?)插入到TEAM中
- Hibernate:将(player_name, id)值(?, ?)插入到PLAYER中
- Hibernate:将(player_name, id)值(?, ?)插入到PLAYER中
- Hibernate:将(player_name, id)值(?, ?)插入到PLAYER中
- Hibernate:更新PLAYER set TEAM_ID=? where id=? Hibernate:更新PLAYER set TEAM_ID=? where id=? Hibernate:更新PLAYER set TEAM_ID=? where id=?
Team team = createTeam(2) // creates team with 2 player ids={1,2}
session.saveOrUpdate(team);
我期望孤儿球员被删除,但是我得到了以下内容:
Hibernate:从TEAM表中选择team_.id,team_.team_name作为team2_0_的值,条件为team_.id=?
Hibernate:从PLAYER表中选择player_.id,player_.player_name作为player2_1_的值,条件为player_.id=?
Hibernate:从PLAYER表中选择player_.id,player_.player_name作为player2_1_的值,条件为player_.id=?
Hibernate:将PLAYER表中的TEAM_ID设置为null,条件为TEAM_ID=?
Hibernate:将PLAYER表中的TEAM_ID设置为给定值,条件为id=?
Hibernate:将PLAYER表中的TEAM_ID设置为给定值,条件为id=?
这导致孤儿球员(id = 3)未被删除,而是被断开连接...
有什么想法我做错了什么吗?
createTeam()
方法是做什么的? - dcernahoschicreateTeam()
函数内部的代码吗? - dcernahoschi