1

Assume we have Student and College

class Student {

    private Long id;
    //...

    @ManyToOne()
    @JoinColumn(name = "college_id")
    private College college;
}

public class College {

    private Long id;
    //...

    @OneToMany(mappedBy = "college")
    private List<Student> studentList;
}

Now if I want to use specification to query with multiple criterias like Example Answer and one criteria is college_id which stored in student table, how should I query without get the College?

I currently have a working example here which is the same from the link. However, I think root.get("college").get("id") is actually not necessary. Is there other way to do it (directly on the column)?

@Override
    public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        Predicate p = criteriaBuilder.conjunction();
        //...
        if ({college_id}) {
            p.getExpressions().add(criteriaBuilder.equal(root.get("college").get("id"), {college_id}));
        }
        return p;
    }
SomeOne
  • 23
  • 2

0 Answers0