Java Spring REST API Handling Many Optional Parameters

前端 未结 3 653
执念已碎
执念已碎 2021-01-05 10:18

I\'m currently messing around with a Spring Boot REST API project for instructional purposes. I have a rather large table with 22 columns loaded into a MySQL database and am

3条回答
  •  星月不相逢
    2021-01-05 11:09

    You can do this easily with a JpaSpecificationExecutor and a custom Specification: https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

    I would replace the HashMap with a DTO containing all optional get params, then build the specifications based on that DTO, obviously you can also keep the HashMap and build the specification based on it.

    Basically:

    public class VehicleFilter implements Specification
    {
        private String art;
        private String userId;
        private String vehicle;
        private String identifier;
    
        @Override
        public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb)
        {
            ArrayList predicates = new ArrayList<>();
    
            if (StringUtils.isNotBlank(art))
            {
                predicates.add(cb.equal(root.get("art"), art));
            }
            if (StringUtils.isNotBlank(userId))
            {
                predicates.add(cb.equal(root.get("userId"), userId));
            }
            if (StringUtils.isNotBlank(vehicle))
            {
                predicates.add(cb.equal(root.get("vehicle"), vehicle));
            }
            if (StringUtils.isNotBlank(identifier))
            {
                predicates.add(cb.equal(root.get("identifier"), fab));
            }
    
            return predicates.size() <= 0 ? null : cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    
    // getter & setter
    }
    

    And the controller:

    @RequestMapping(value = "/{ticket}/count", method = RequestMethod.GET)
    public long getItemsCount(
        @PathVariable String ticket,
        VehicleFilter filter,
        HttpServletRequest request
    ) throws Exception
    {
        return vehicleService.getCount(filter);
    }
    

    Service:

    @Override
    public long getCount(VehicleFilter filter)
    {
        return vehicleRepository.count(filter);
    }
    

    Repository:

    @Repository
    public interface VehicleRepository extends JpaRepository, JpaSpecificationExecutor
    {
    }
    

    Just a quick example adapted from company code, you get the idea!

提交回复
热议问题