Reputation: 44114
These are my entities
@Entity
public class User {
@ManyToMany(mappedBy="admins")
private Set<Game> adminForGames = new HashSet<Game>();
@Entity
public class Game {
@ManyToMany
@JoinTable(
name="Game_adminUsers",
joinColumns=@JoinColumn(name="Game_id"),
inverseJoinColumns=@JoinColumn(name="User_id")
)
private Set<User> adminUsers = new HashSet<User>();
And this is how I create a new Game
:
Game game = new Game(index, name);
game.getAdminUsers().add(someUser);
em.persist(game);
As you can see I don't update the someUser
to add the new game to his adminForGames
, though according though the JPA spec this is my responsibility.
Still, it works fine, which is logical because the User
record doesn't actually need to be written to (because the relationship uses a join table).
Does it work "by chance" (my implementation is Hibernate) or am I actually doing this correctly?
Upvotes: 0
Views: 463
Reputation: 30025
My understanding from the JPA spec is that it is the user's responsibility to set correct relations in memory.
For the database it is sufficient to set the owning side of the relationship (and that is what you did). So (from theory) it should not work if you set the non-owning side only.
Upvotes: 1