I have a one way @OneToMany relationship between a Team and Player class. I would like to save a Team object among your Players. Player's identifier IS COMPOUND by Team foreign key and list index as follows. I have a mapping like this one because i need to save Team and your Players ate the same time.
@Entity
public class Team {
@Id
@GeneratedValue
private Integer id;
@CollectionOfElements
@JoinTable(
name="PLAYER",
joinColumns=@JoinColumn(name="TEAM_ID"))
@IndexColumn(name="PLAYER_INDEX")
private List<Player> playerList = new ArrayList<Player>();
}
@Embeddable
public class Player {
// Player's getter's and setter's
}
So if i use the following
Team team = new Team();
team.getPlayerList().add(new Player());
team.getPlayerList().add(new Player());
session.save(team); // It works!
It happens whether you use @CollectionsOfElements, Player class need a @Embeddable annotation, not a @Entity. JPA does not allows @Entity and @Embeddable at the same time. Player is also a @Entity – it has relationship with other entities.
Has someone an idea about i could save a Team and a Player (ONE WAY RELATIONSHIP) by using CascadeType.PERSIST with @Entity in the Player class instead of @Embeddable ?
Remember that COMPOUND primary key needs to be assigned before saving but Team's identifier and PlayerList index position could play the role of Player's compound primary key
regards,
Best Answer
The below solution shows a composite key for Player that consists of Team and the position in the list of players in that team. Saves cascade from team to players.
Team.java
Player.java
PlayerId.java
This test below:
gives the following log output:
The last line shows the
toString
forTeam
andPlayer
, which shows how the numbers are assigned (the index of the list). Other entities can refer the Player (by team_id and player_idx).