当前位置: 代码迷 >> 综合 >> springboot JPA的JPQL中判断查询条件是否为空
  详细解决方案

springboot JPA的JPQL中判断查询条件是否为空

热度:90   发布时间:2023-10-15 07:08:26.0

springboot的版本号为:2.1.4.RELEASE

postgres版本号为:PostgreSQL 10.5, compiled by Visual C++ build 1800, 64-bit

建表SQL如下:

CREATE TABLE "crt"."employee" (
"id" int8 DEFAULT nextval('"crt".employee_id_seq'::regclass) NOT NULL,
"age" int4 DEFAULT 25,
"emp_name" text COLLATE "default",
"salary" numeric(7,2),
"create_time" timestamp(6),
CONSTRAINT "employee_pkey" PRIMARY KEY ("id"),
CONSTRAINT "employee_salary_check" CHECK ((salary > (0)::numeric))
)
WITH (OIDS=FALSE)
;ALTER TABLE "crt"."employee" OWNER TO "postgres";

controller:

    @PostMapping("/null/args/test")public List<Employee> nullArgsTest(@RequestBody Employee emp){return empService.nullArgsTest(emp.getEmpName(),emp.getAge());}

service:

    public List<Employee> nullArgsTest(String empName, int age) {return employeeRepository.nullArgsTest(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> nullArgsTest(@Param("empName")String empName, @Param("age")int age);

当入参:{"empName":"","age":18}时查询成功;

当入参:{"empName":""}时查询成功;

但是当入参全部不传时,即{},时报错如下:

org.postgresql.util.PSQLException: ERROR: operator does not exist: text = bytea
  建议:No operator matches the given name and argument type(s). You might need to add explicit type casts.

原因未知!有待探索!