1

I have a class that needs to manage a mapping of two other classes, but I need to isolate it to only the records it cares about. Basically, you have a player who might have an account on any number of game servers. Each server has to manager the player-to-account mapping for only its server. In these stub classes, I'm omitting a lot of unnecessary fields. Assume

// player has no collections or associations in the class
public class Player {
    @Id @GeneratedValue @Column private int id;
    // other crap about the actual person
}

// character has an association to the player and the server
public class LocalCharacter {
    @Id @GeneratedValue @Column private int id;
    @ManyToOne private Player player;
    @ManyToOne private GameServer server;
    // other crap about this person's character on this server
}

// game server needs to know who all is on it, but it needs to be mapped to the player
public class GameServer {
    @Id @GeneratedValue @Column private int id;
    @/* no idea here */ private Map<Player, LocalCharacter> localCharacters;
}

I'm not sure how to construct this mapping. I know if I just wanted a Set<LocalCharacter> I could do that with an @OneToMany. I know I could do a join fetch on the player and construct the Map myself, but that seems lame - I'd like hibernate to do it for me! :-) How can I make this happen?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • What have you tried? You can't use a variation of the approach detailed in example 7.11 in the docs? (https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch07.html) – Mark Mar 18 '15 at 20:28
  • All I've tried is what I know works, making the Set and manually constructing the maps I need. – corsiKa Mar 18 '15 at 20:32
  • So why not try some of those map annotations? – Mark Mar 18 '15 at 21:43
  • Take a look at this auestion: http://stackoverflow.com/questions/2327971/how-do-you-map-a-map-in-hibernate-using-annotations – Radek Mar 18 '15 at 23:31

1 Answers1

0

You need to use a @MapKeyJoinColumn for that:

public class GameServer {

    @Id 
    private Integer id;

    @OneToMany(mappedBy="server")       
    @MapKeyJoinColumn(name="player_id")
    private Map<Player, LocalCharacter> localCharacters = new HashMap<>();

}

Check this answer for a detail explanation of various java.util.Map associations.

Community
  • 1
  • 1
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911