springboot JPA的JPQL中判断查询条件是否为空
环境:
springboot postgres
controller:
@PostMapping("/demo/Demo01") public List<Employee> Demo01(@RequestBody Employee emp){ return empService.Demo01(emp.getEmpName(),emp.getAge()); }
service:
public List<Employee> Demo01(String empName, int age) { return employeeRepository.Demo01(empName,age); }
repository:
@Query(nativeQuery=true,value="select * from Employee where 1=1 and " + " case when :empName is not null and :empName!='' then emp_Name = :empName else 1=1 end " + " and " + " case when :age>0 then age=:age else 1=1 end ") List<Employee> Demo01(@Param("empName")String empName, @Param("age")int age);
核心处理的地方:
case when :empName is not null and :empName!='' then emp_Name = :empName else 1=1 end