java - 如何注释 map 以连接两个看似不相关的类?

标签 java hibernate jpa orm hibernate-mapping

我有一个类需要管理其他两个类的映射,但我需要将其隔离到仅它关心的记录。基本上,您的玩家可能在任意数量的游戏服务器上拥有帐户。每个服务器必须仅管理其服务器的玩家到帐户映射。在这些 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/

相关文章:

java - Hibernate:如何测试 JPA/Hibernate Predicate 实例?

jpa - 使用命名空间,http ://xmlns. jcp.org/xml/ns/persistence/导致错误

java - Autowired 类的 Cobertura 问题

java - 未在指定日期范围内获取 Jasper 报告

java - Spring : @Transactional @Scheduled method throws TransactionException

java - 数据库未返回 native 生成的标识值

java - 如何将数据库生成的随机唯一值分配给Hibernate POJO的字段

java - 何时使用 ServiceTracker 与 ServiceReference

java - 如何在随机生成数字后返回单位数计数(Java,数组)

hibernate - 为什么 Hibernate 会尝试加载 "not-found=ignore"关联?