我有一个类需要管理另外两个类的映射,但我需要将它隔离到它关心的记录。基本上,您有一个可能在任意数量的游戏服务器上拥有帐户的玩家。每个服务器必须仅管理其服务器的播放器到帐户映射。在这些存根类中,我省略了许多不必要的字段。假设
// 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
并自己构建地图,但这似乎很蹩脚 - 我希望冬眠来为我做! :-)我怎样才能实现这一目标?
答案 0 :(得分:0)
您需要使用@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的详细说明。