Java Hibernate Criteria。从子类列表中选择子类属性

时间:2016-01-28 16:08:51

标签: java hibernate

我有三个Java hibernate个实体。我希望使用hibernate criteria让所有在其选择列表中选择具有特定ID的用户。

用户实体:

  @Entity
  @Table(name="users")
  public class User {
      ...
      @ManyToMany
      private List<UserPick> picks = new ArrayList<UserPick>(0);
      ...

UserPick实体:

@Entity
@Table(name="usersPicks")
public class UserPick {
...
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "fk_user") 
  private User user;

  @ManyToOne
  private MatchPick pick;
  ...

我希望获得所有使用特定pick.id选择的用户,例如:

// return all users if exist pick with pickId in picks list
public List<User> getUsersByPick(int pickId) {
    Criteria criteria = session.createCriteria(User.class);
    criteria... //
    return criteria.list();
}

// Goal is get target but using Hibernate criteries
public List<User> getUsersByPick(int pickId) {
    Criteria criteria = session.createCriteria(User.class);
    List<User> users = criteria.list();
    List<User> target = new List<>();

    for(User u:users)
       for(UserPick p:u.getPicks())
         if(p.getId == pickId)target.add(u);

    return target;
}

1 个答案:

答案 0 :(得分:0)

为我工作。

   public List<User> getUsersByPick(int pickId) {
        Criteria criteria = session.createCriteria(User.class)
        .createCriteria("userPicks", "picks")
        .createCriteria("pick", "pick")
        .add( Restrictions.eq("pick.id",pickId) );
        return criteria.list();
    }