0

I have 2 classes with a relation @OneToOne: User and Player.

User contain a player:

@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...
}

I want to query user with only nickname and player, and with player I don't want all attributes, I only want 2.

This is what I have now:

    //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));

I am getting only nickname, id and the player, but how can I set projections to the player to only get player.level and not all the attributes?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Raxkin
  • 387
  • 1
  • 3
  • 18

2 Answers2

0

Its think it is exactly as you suggest:

projectionList.add(Projections.property("player.level"), "player.level");
KernelKoder
  • 746
  • 5
  • 15
0

First create alias for the JoinColumn table Player in User & then refer it in your 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));

I hope this helps you.

OO7
  • 2,785
  • 1
  • 21
  • 33