For example, lets say I want to assign a player to a team using the user and team's primary keys:
myEjb.java
public void assignPlayer(Integer teamId, Integer playerId) {
Team team = em.find(Team.class, teamId);
team.getPlayers().add(new Player(playerId));
em.merge(team);
.
.
}
Is it wrong to do this? I feel like I'm saving myself an extra DB read by wrapping the player primary key in the object instead of first doing:
Player player = em.find(Player.class, playerId)
No, it's not a good idea.
First, the call to merge() is not necessary.
Second, there is a standard method to create an entity from an ID, without executing any query: getReference()
.
Team team = em.find(Team.class, teamId);
team.getPlayers().add(em.getReference(Player.class, playerId));
At least with getReference(), you get a real, managed entity. And if the code, later in the transaction, happens to call a method on that player, it won't get null
as a result: JPA will load the player state, and return the correct value.