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

本文详细介绍了如何在SpringBoot2.1.4版本中整合PostgreSQL10.5数据库,包括创建员工信息表的SQL语句,以及通过Controller、Service和Repository实现对数据库的动态查询操作。特别关注了当参数为空时的SQL拼接问题,避免了类型不匹配的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

原因未知!有待探索!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值