Hi,
Take a look at the following classes (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);
}
}
Notice addPlayer: team's id and player's teamId references the same instance so
AssertEquals(team.getId(), player.getPlayerId().getTeamId());
should work, don't ?
Hibernate will not save -1 value because i have declared a generator strategy (default to auto) If an identifier generator is declared, Hibernate takes care of the primary key value assignment. I have assined -1 to Team's id IN ORDER TO SHARE ITS REFERENCE in Player's id (when calling addPlayer method) as follows
@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;
}
}
But when i call (Take a special look at addPlayer)
Team team = new Team();
Player player = new Player();
// teamId property in PlayerId references Team id
team.addPlayer(player);
session.save(team);
And i see the database i get
PLAYER
TEAM_ID PLAYER_INDEX
-1 0
TEAM
ID
1
And when i compare after saving
AssertEquals(team.getId(), player.getPLayerId().getTeamId()); // It does not works! why ?
log outputs
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 (?, ?)
So do you know why Hibernate lost Team's id reference in Player's teamId property after saving a team and its players ?