2

嗨,我正在编写一个 Specification.toPredicate() 方法来根据以标准形式输入的搜索条件搜索实体。我让它用于搜索父实体,但需要搜索子实体的属性(它们被映射并保存在一个集合中)。映射是多对多的。

对子属性的搜索将返回在输入的子属性上搜索匹配的所有父项。

例如,使用教师 [家长] 和学生 [孩子] 之间的简单关系

        @Entity
        class Teacher {
           @Id
           @Column(name = "ID")
           private Long id; 

           @Column(name = "NAME")
           private String name;

           @ManyToMany(fetch = FetchType.EAGER)
           @JoinTable(name = "TEACHER_PUPIL",
                                 joinColumns =
           @JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID"),
                                 inverseJoinColumns =
           @JoinColumn(name = "PUPIL_ID", referencedColumnName = "ID"))
           Set<Pupil> pupils;

                     // etc.

     }

        @Entity
        class Pupil {
           @Id
           @Column(name = "ID")
           private Long id;

           @Column(name = "NAME")
           private String name;
           // etc.

    }

            public class ClassSpecifications {


                public static Specification<Teacher> filterCriteria(final MyCustomForm myForm) {

                              return new Specification<Teacher>() {

                                @Override
                                public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                                    List<Predicate> predicates = new ArrayList<Predicate>();
                                                // *** this works fine.  
                                if (myForm.getSearchName() != null) {                   
                                                            Expression<String> expression = root.get("name");
                                        predicates.add(criteriaBuilder.like(criteriaBuilder.upper(expression), "%" + myForm.getSearchName().toUpperCase() + "%"));  
                                }


                                               if (myForm.getPupilNameSearch() ! = null) {
                                                // HERE SEARCH List for the pupil's name like.
                                                }

                                criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                                return null;

                          }


                    }





   @Repository
   public interface TeacherDAO extends JpaRepository<Teacher, Long> , JpaSpecificationExecutor<Teacher>{

    }

// 调用将是:

teacherDAO.findAll(ClassSpecifications.filterCriteria(searchForm));

谢谢。

4

1 回答 1

1
SetJoin<Teacher, Pupil> transactions = root.joinSet("pupils");              
Expression<String> expression = transactions.get("name");
predicates.add(criteriaBuilder.like(criteriaBuilder.upper(expression), "%" + myForm.getPupilNameSearch().toUpperCase()+ "%"));
于 2013-09-09T16:36:00.487 回答