我正在使用Spring JPA规范根据表行ID过滤搜索结果。但是结果不会按搜索条件过滤。我认为执行流程是错误的。
实体人:
public class Person{
.....
@OneToMany
List<Role> roles;
}
Entity Role:
public class Role{
....
UUID id;
@ManyToOne(fetch = FetchType.EAGER)
Person person;
}
规范服务类别:
@Override
public Page<Person> PersonSearch(final Pageable pageable) {
UUID id ="456d5716-fb6b-4a4d-91b4-4ffddb1743b8";
Person prsn = new Person();
Specification<Person> specification = Builder
.build(prsn);
specification = Builder.addIds(id,specification);
final Page<Person> page = repository.findAll(specification, pageable);
final List<Person> list = new ArrayList<>();
page.forEach(item -> list.add(list.add(item));
return new PageImpl<>(list, pageable, page.getTotalElements());
}
Builder类别:
public static Specification<Person> build(final Person prsn) {
final List<Specification<Person>> specs = new ArrayList<>();
hasId(prsn,specs);
Specification<Person> result = specs.get(0);
for (int i = 1; i < specs.size(); i++) {
result = Specifications.where(result).and(specs.get(i));
}
return result;
}
public static Specification<Person> hasId(final Person prsn final List<Specification<Person>> specs) {
if (StringUtils.isNotEmpty(example.getId())) {
specs.add(PersonSpecifications.hasId(example.Id()));
}
}
public static Specification<Person> addIds(final UUID id, final Specification<Person> specs) {
Specification<Person> result = specs;
if (ud != null) {
result = Specifications.where(result).and(PersonSpecifications.addIds(id));
}
return result;
}
规范类别:
public static Specification<Person> hasId(final UUID id) {
return (root, query, cb) -> cb.equal(root.get("uuid"), id);
};
}
public static Specification<Person> addIds(final UUID id) {
return (root, query, cb) -> {
query.distinct(true);
Join<Person, Role> role = root.join("roles",
JoinType.INNER);
return cb.equal(role.get("uuid"), id);
};
}
表格行:
“ 406d5716-fb6b-4a4d-91b4-4ffddb1743b8”,“ e5c777d9-554a-43f2-be4e-26cb5f561a84”;
“ 456d5716-fb6b-4a4d-91b4-4ffddb1743b8”,“ e5c777d9-554a-43f2-be4e-26cb5f561a84”;
根据搜索条件执行repository.findAll(规范,可分页)后,我应该在搜索结果中仅得到一行(“ 456d5716-fb6b-4a4d-91b4-4ffddb1743b8”,“ e5c777d9-554a-43f2-be4e” -26cb5f561a84“),但我同时获得了两行。
有人可以帮助我吗?预先感谢。