Search code examples
javahibernatecriteria

get Criteria.list by key


I have classes:

Entity
@Table(name = "oldusers")
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
   ......
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "userId", cascade =      CascadeType.ALL)
    List<User> usertList= new ArrayList<>(0);

    public List<User> getUserList() {
        return userList;
    }

and

@Table(name = "user")
public class Usert implements Serializable {
    int userId;
    int position;
    String name;
    List<Exercise> list = new ArrayList<>(0);
    OldsUser userId;

@ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parentid")
    public OldUser getUserId() {
        return this.userId;
    }
}

I need get all User by idOldUser.For that I have written below code

Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.eq("parentid", idOldUser));

But nothing get :(


Solution

  • It was a bit complicated but I think what you should need it changing criteria like this:

    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("userId.id", idOldUser));
    

    you parentId is actually oldUser. An you initialized your OldUser as userId in you Usert class (I belive Usert class shows the User class, and the class at the top shows the OldUser class depending on your comment)