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
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!