JPA / Hibernate - 如何获取EmbeddedId?

时间:2012-06-02 18:53:45

标签: java hibernate jpa

我有以下实体:

@Entity(name = "game_users")
public class GameUser {

    private GameUsersPK primaryKey;

    @EmbeddedId
    public GameUsersPK getPrimaryKey() {
        return primaryKey;
    }
    ...
}

使用以下PK:

@Embeddable
public class GameUsersPK implements Serializable {
    @ManyToOne
    private Game game;

    @ManyToOne
    private User user;
    ...
}

当我通过执行:

查询GameUser
GameUser gameUser = em.createQuery("from game_users", GameUser.class).setMaxResults(1).getSingleResult();

我注意到Hibernate正在执行两个查询 - 一个来自game_users,另一个来自games left outer join users

我可以让Hibernate在一个查询中获取所有实体 - from game_users, games, users吗?

感谢。

1 个答案:

答案 0 :(得分:2)

select gu from GameUser gu
left join fetch gu.primaryKey.game
left join fetch gu.primaryKey.user

阅读Hibernate documentation about HQL and associations