springjpa合集地址:https://www.jianshu.com/nb/38441578
JpaRepository接口已經能幫我們實現大部分的增刪改查工作,本文重點描述查詢這一部分。
JpaRepository已經實現的查詢功能有如下幾點
- 查詢全部
- id查詢
- 排序查詢全部
- 分頁排序查詢全部
- 自定義接口名查詢(例如findByNameLike,findByAgeLessThan等等)
- 實例查詢Example
大量的查詢工作JpaRepository已經幫我們做了,但是還有一些查詢功能JapRepository是沒有辦法實現的,例如範圍查詢等等。要實現類似與多條件搜索性質的功能的查詢我們可以使用JpaSpecificationExecutor。
廢話不多說直接上代碼
//我們自己的接口除了繼承JpaRepository,同時繼承JpaSpecificationExecutor
public interface User5Repository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
@Service
public class User5Service {
@Autowired
private User5Repository user5Repository;
public List<User> findAll(UserDTO userDTO) {
return user5Repository.findAll(new Specification<User>() {
@Nullable
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
//取出字段
Path<Integer> age = root.get("age");
Path<String> name = root.get("name");
Path<String> city = root.get("city");
//設置條件
Predicate predicate = criteriaBuilder.conjunction();//where 1=1
if (userDTO.getAgeStart() != null) {
predicate.getExpressions().add(criteriaBuilder.greaterThanOrEqualTo(age, userDTO.getAgeStart()));//and age>=?
}
if (userDTO.getAgeEnd() != null) {
predicate.getExpressions().add(criteriaBuilder.lessThanOrEqualTo(age, userDTO.getAgeEnd()));//and age<=?
}
if (StringUtils.isNotBlank(userDTO.getName())) {
predicate.getExpressions().add(criteriaBuilder.like(name, "%" + userDTO.getName() + "%"));//and name like '%?%'
}
if (StringUtils.isNotBlank(userDTO.getCity())) {
predicate.getExpressions().add(criteriaBuilder.equal(city, userDTO.getCity()));//and city=?
}
return predicate;
}
});
}
}