springdata JPA使用教程

2019-12-26  本文已影响0人  杨康他兄弟
Criteria查询

这是springdata中最强大,最灵活的使用方式了,几乎可以满足所有的查询场景。用法如下:

  1. 首先Repository要继承JpaSpecificationExecutor
public interface DemoRepository extends JpaRepository< DemoEntity,String>, JpaSpecificationExecutor {
  ......
}
  1. 构造动态查询,多条件查询
package com.hello.springdata.jpa.service.impl;

@Service
public class ServiceServiceImpl implements ServiceService {
    private Logger logger = LoggerFactory.getLogger(ServiceServiceImpl.class);

    @Autowired
    DemoRepository  demoDao ;

    @Override
    public Page<TDemoServiceEntity> findPage(Map<String, String> params, Pageable pageable) {
        Specification querySpeci = (Specification) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            //服务名模糊查询
            String serviceName = params.get("serviceName");
            if(!StringUtils.isEmpty(params.get("serviceName"))) {
                predicates.add(criteriaBuilder.like(root.get("serviceName"), "%" + serviceName + "%"));
            }
            //服务IP查询
            String serviceIp = params.get("serviceIp");
            if(!StringUtils.isEmpty(serviceIp)) {
                predicates.add(criteriaBuilder.equal(root.get("serviceIp"), serviceIp ));
            }
            //服务类型查询
            String serviceType = params.get("serviceType");
            if(!StringUtils.isEmpty(serviceType)) {
                predicates.add(criteriaBuilder.equal(root.get("serviceType"), serviceType ));
            }
            //服务状态查询
            String serviceStatus = params.get("serviceStatus");
            if(!StringUtils.isEmpty(serviceStatus)) {
                predicates.add(criteriaBuilder.equal(root.get("serviceStatus"), serviceStatus ));
            }
            //服务创建时间查询
            String startTime = params.get("startTime");
            if(!StringUtils.isEmpty(startTime)) {
                predicates.add(criteriaBuilder.greaterThan(root.get("createTime"), startTime ));
            }
            //服务创建时间查询
            String endTime = params.get("endTime");
            if(!StringUtils.isEmpty(endTime)) {
                predicates.add(criteriaBuilder.lessThan(root.get("createTime"), endTime ));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return demoDao.findAll(querySpeci, pageable);
    }
}
上一篇下一篇

猜你喜欢

热点阅读