2

I want use the spring JPA specification join function

This is my code for the tables:

  1. Table InStudent
  2. Table InParent

    public static Specification<InStudent> filterByKeywordAndStatus(final String keyword) {
    return (Root<InStudent> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
        List<Predicate> predicates = new ArrayList<>();
    
        if (StringUtils.hasText(keyword)) {
    
            predicates.add(
                    cb.or(
                            cb.like(root.get(InStudent_.name), "%" + keyword + "%"),
                            cb.like(root.get(InStudent_.address), "%" + keyword + "%"),
                            cb.like(root.get(InStudent_.phone), "%" + keyword + "%")
                    )
            );
        }
    
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
    

    }

How can I join table inStudent and inParent within the specification?

Thom
  • 14,013
  • 25
  • 105
  • 185
dsg
  • 45
  • 1
  • 8
  • 1
    Possible duplicate of [Joining two table entities in Spring Data JPA](https://stackoverflow.com/questions/19977130/joining-two-table-entities-in-spring-data-jpa) – K.Nicholas Jul 09 '17 at 14:15
  • You did not include the relationship in your code. Anyway to use a join would be like `Join parent = root.join(InStudent_.parent);` asuming the field which specifies the relation is `parent`. – Ranjeet Jul 09 '17 at 15:22
  • Hello, if the answer helped you don't forget to accept/upvote it. – Cepr0 Jul 12 '17 at 18:56

1 Answers1

3

Try something like this (if I've understood you correctly):

public static Specification<Student> filterByKeywordAndStatus(String keyword, String parentStatus) {

    return (student, query, cb) -> {

        Join<Student, Parent> joinParent = student.join("parent");

        return cb.and(
                cb.or(
                   cb.like(student.get("name"), "%" + keyword + "%"),
                   cb.like(student.get("address"), "%" + keyword + "%"),
                   cb.like(student.get("phone"), "%" + keyword + "%")
                ),
                cb.like(joinParent.get("status"), "%" + parentStatus + "%"));
    };
}
Cepr0
  • 28,144
  • 8
  • 75
  • 101