我有一个类需要管理其他两个类的映射,但我需要将其隔离到仅它关心的记录。基本上,您的玩家可能在任意数量的游戏服务器上拥有帐户。每个服务器必须仅管理其服务器的玩家到帐户映射。在这些 stub 类中,我省略了很多不必要的字段。假设
// 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;
}
我不知道如何构建这个映射。我知道我是否只是想要一个 Set<LocalCharacter>
我可以用 @OneToMany
来做到这一点。我知道我可以做 join fetch
在播放器上并自己构建 map ,但这似乎很蹩脚 - 我希望 hibernate 为我做这件事! :-) 我怎样才能做到这一点?
最佳答案
您需要使用@MapKeyJoinColumn为此:
public class GameServer {
@Id
private Integer id;
@OneToMany(mappedBy="server")
@MapKeyJoinColumn(name="player_id")
private Map<Player, LocalCharacter> localCharacters = new HashMap<>();
}
查看此答案以获取 various java.util.Map associations 的详细说明.
关于java - 如何注释 map 以连接两个看似不相关的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29131495/