Hibernate投影标准

时间:2015-05-07 09:03:43

标签: java hibernate

我有2个关系为@OneToOne的课程:UserPlayer

用户包含播放器:

@Entity
@Table(name = "user")
public class User {
    @Column(name = "nickname")
    private String nickname;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "id_player")
    private Player player;

   //getters and setters...
}

我想查询的用户只有nicknameplayer,而player我不想要所有属性,我只想要2。

这就是我现在所拥有的:

    //Projections for the class User
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("id"), "id");
    projectionList.add(Projections.property("nickname"), "nickname");
    projectionList.add(Projections.property("player"), "player");

    Criteria criteria = session.createCriteria(User.class);
    criteria.setFirstResult(player.getPvpRank() - 5);
    criteria.setMaxResults(11);
    criteria.createAlias("player", "p");
    criteria.addOrder(Order.asc("p.pvpRank"));
    criteria.setProjection(projectionList);
    criteria.setResultTransformer(Transformers.aliasToBean(User.class));

我只获得nicknameidplayer,但如何设置播放器的投影只能获得player.level而不是所有属性?< / p>

2 个答案:

答案 0 :(得分:0)

它认为完全按照你的建议:

projectionList.add(Projections.property("player.level"), "player.level");

答案 1 :(得分:0)

首先为Player&amp;中的JoinColumn表User创建别名 然后在您的projectionList 中引用它。

Criteria criteria = session.createCriteria(User.class);
criteria.createAlias("player", "p");
projectionList.add(Projections.property("p.level"), "player");
...
criteria.setProjection(projectionList);
criteria.setResultTransformer(Transformers.aliasToBean(User.class));

我希望这会对你有所帮助。