0

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?

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301

2 Answers2

1

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.

Matt Handy
  • 29,855
  • 2
  • 89
  • 112
  • Ok, so I mustn't expect that I can get correct info from that same `User` instance's `adminForGames` field after the transaction? I don't need to do that anyway. – Bart van Heukelom Nov 03 '11 at 10:47
  • 1
    That's correct. Alternatively you could refresh the User from the database to get correct adminForGames informtion. – Matt Handy Nov 03 '11 at 14:31
0

This isn't "chance." This is how JPA is expected to work.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710