您好我正在编写一个Specification.toPredicate()方法,根据以标准格式输入的搜索条件搜索实体。我让它在父实体上搜索,但需要搜索子项的属性(映射并保存在Set中)。映射是多对多的。
对子属性的搜索将返回搜索在输入的子属性上匹配的所有父项。
例如,使用Teacher [Parent]和Pupil [Child]
之间的简单关系 @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));
感谢。
答案 0 :(得分:0)
SetJoin transactions = root.joinSet(“pupils”);
Expression<String> expression = transactions.get("name");
predicates.add(criteriaBuilder.like(criteriaBuilder.upper(expression), "%" + myForm.getPupilNameSearch().toUpperCase()+ "%"));