问题简览:
SpringBoot+JPA,Pageable+Specification:
Page users = userRepository.findAll(query, pageable);
Long pageTotal = userRepository.countAll(query);
其中 users
的 findAll
正常运行,但添加 countAll
之后,直接编译报错:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adminController': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.gxnmgcy.repository.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.lang.Long com.gxnmgcy.repository.UserRepository.countAll(org.springframework.data.jpa.domain.Specification)! Reason: Failed to create query for method public abstract java.lang.Long com.gxnmgcy.repository.UserRepository.countAll(org.springframework.data.jpa.domain.Specification)! No property countAll found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.lang.Long com.gxnmgcy.repository.UserRepository.countAll(org.springframework.data.jpa.domain.Specification)! No property countAll found for type User!
AdminController:
// 排序
Sort sort = Sort.by(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(page-1, pageSize, sort);
// 动态查询
Specification<User> query = (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
predicates.add(criteriaBuilder.equal(root.get("type"), 1));
if (name != null && !"".equals(name)) {
predicates.add(criteriaBuilder.like(root.get("realName"), "%"+name+"%"));
}
if (phone != null && !"".equals(phone)) {
predicates.add(criteriaBuilder.like(root.get("phone"), "%"+phone+"%"));
}
if (idCard != null && !"".equals(idCard)) {
predicates.add(criteriaBuilder.like(root.get("idCard"), "%"+idCard+"%"));
}
criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
criteriaQuery.orderBy(criteriaBuilder.desc(root.get("id")));
return criteriaQuery.getRestriction();
};
// 多条件查询
Page<User> users = userRepository.findAll(query, pageable);
Long pageTotal = userRepository.countAll(query);
UserRepository:
public interface UserRepository extends JpaRepository<User, Integer>
Page<User> findAll(Specification<User> query, Pageable pageable);
Long countAll(Specification<User> query);
}
拓展
此外,若获取到 pageTotal 后,若想组装数据回前端:{count:pageTotal, list:users},我的做法是:
PageView pageView = new PageView(pageTotal, users.getContent());
@Data
class pageView {
private Long pageTotal;
private List<Map> list;
}
但此时ide会报红,需单独创建 setList 方法:public void setList(List content) {}
请问这里的 List 为什么不能装进 Map 呢