gpt4 book ai didi

java - Spring Data Predicate - 在子集合中搜索属性

转载 作者:行者123 更新时间:2023-11-29 08:58:51 25 4
gpt4 key购买 nike

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

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

例如,使用 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));

谢谢。

最佳答案

SetJoin<Teacher, Pupil> transactions = root.joinSet("pupils");              
Expression<String> expression = transactions.get("name");
predicates.add(criteriaBuilder.like(criteriaBuilder.upper(expression), "%" + myForm.getPupilNameSearch().toUpperCase()+ "%"));

关于java - Spring Data Predicate - 在子集合中搜索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com