查看以下类(UNIdirectional @OneToMany)
@Entity
public class Team {
private Integer id = -1;
@Id
@GeneratedValue
public Integer getId() {
return this.id;
}
private List<Player> playerList;
@OneToMany
@Cascade(CascadeType.SAVE_UPDATE)
@JoinColumn(name="TEAM_ID", insertable=false, updateable=false)
public List<Player> getPlayerList() {
return this.playerList;
}
public void addPlayer(Player player) {
player.setId(new PlayerId(getId(), getPlayerList().size()));
playerList.add(player);
}
}
注意addPlayer:团队的id和玩家的teamId引用相同的实例,所以
AssertEquals(team.getId(), player.getPlayerId().getTeamId());
应该工作,不是吗?
Hibernate不会保存-1值,因为我已经声明了生成器策略(默认为auto)如果声明了标识符生成器,Hibernate将负责主键值赋值。我已经确定-1为Team的id以命令在玩家的id中分享它的参考(当调用addPlayer方法时),如下所示
@Embeddable
public class PlayerId implements Serializable {
private Integer teamId;
private Integer playerIndex;
// required no-arg constructor
public PlayerId () {}
public PlayerId(Integer teamId, Integer playerIndex) {
this.teamId = teamId;
this.playerIndex = playerIndex;
}
@Column(name="TEAM_ID", nullable=false)
public Integer getTeamId() {
return this.teamId;
}
@Column(name="PLAYER_INDEX", nullable=false)
public Integer getPlayerIndex() {
return this.playerIndex;
}
// getters and setters
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanceof PlayerId))
return false;
PlayerId other = (PlayerId) o;
if(!(getTeamId().equals(other.getTeamId()))
return false;
if(!(getPlayerIndex().equals(other.getPlayerIndex()))
return false;
return true;
}
}
但是当我打电话时(特别注意一下addPlayer)
Team team = new Team();
Player player = new Player();
// teamId property in PlayerId references Team id
team.addPlayer(player);
session.save(team);
我看到我得到的数据库
PLAYER
TEAM_ID PLAYER_INDEX
-1 0
TEAM
ID
1
保存后我比较
AssertEquals(team.getId(), player.getPLayerId().getTeamId()); // It does not works! why ?
日志输出
INSERT INTO TEAM VALUES()
// SELECT BEFORE SAVING OR UPDATING WHEN USING A COMPOUND PRIMARY KEY
SELECT * FROM PLAYER WHERE TEAM_ID = ? AND PLAYER_INDEX = ?
INSERT INTO PLAYER (TEAM_ID, PLAYER_INDEX) VALUES (?, ?)
所以你知道为什么Hibernate在保存一个团队及其球员之后在Player的teamId属性中丢失了Team的id引用?
答案 0 :(得分:1)
我不确定“维护参考”是什么意思?我也不太清楚你在这里要做什么......
您是否希望Hibernate使用新创建的TEAM_ID
实体的Team
(例如在这种情况下为1)来插入Player
个实例?如果是这样,你通过在@JoinColumn声明中将insertable / updatable指定为false来明确地防止这种情况发生 - 你需要在Player类中将它们移动到getTeamId()
方法。
你能澄清一下你在这里想要达到的目标吗?