Java 如何注释一个映射以连接两个看似无关的类?
我有一个类需要管理另外两个类的映射,但我需要将它隔离到它关心的记录。基本上,你有一个玩家可以在任意数量的游戏服务器上拥有一个帐户。每个服务器必须只管理其服务器的播放器到帐户映射。在这些存根类中,我省略了许多不必要的字段。假定Java 如何注释一个映射以连接两个看似无关的类?,java,hibernate,jpa,orm,hibernate-mapping,Java,Hibernate,Jpa,Orm,Hibernate Mapping,我有一个类需要管理另外两个类的映射,但我需要将它隔离到它关心的记录。基本上,你有一个玩家可以在任意数量的游戏服务器上拥有一个帐户。每个服务器必须只管理其服务器的播放器到帐户映射。在这些存根类中,我省略了许多不必要的字段。假定 // player has no collections or associations in the class public class Player { @Id @GeneratedValue @Column private int id; // ot
// 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;
}
我不知道如何构造这个映射。我知道如果我只是想要一套,我可以用一个@OneToMany。我知道我可以在播放器上进行连接提取并自己构建地图,但这似乎很蹩脚——我希望hibernate为我做这件事!:-我如何才能做到这一点?您需要使用以下方法:
public class GameServer {
@Id
private Integer id;
@OneToMany(mappedBy="server")
@MapKeyJoinColumn(name="player_id")
private Map<Player, LocalCharacter> localCharacters = new HashMap<>();
}
查看此答案,了解有关的详细说明。您尝试了什么?您不能使用文档中示例7.11中详述的方法的变体吗?我所做的只是我所知道的工作,制作集合并手动构建我所需要的地图。那么为什么不尝试一些地图注释呢?看看这个评估: