JPA的@Query注解在使用like关键字时且为复杂语句时存在截断后面SQL的BUG。具体如下。
BUG现象
"select t from T t where t.name in (:names) and (t.dz like %:searchKey% or t.hjdz = :searchKey)") ( |
上面的两条语句,第二条执行正常,第一条会出现异常的返回结果,等同于
"select t from T t where t.name in (:names) and (t.dz like %:searchKey% )") ( |
即,整个语句从like往后被截断。
解决方案
方案1:在参数传递过来前就把 %%号拼好,如 searchKey=”a” 改为 searchKey =”%a%” ,@Query中 like 去除%%。
"select t from T t where t.name in (:names) and (t.dz like :searchKey or t.hjdz = :searchKey)") (
方案2:使用concat代替like
"select t from T t where t.name in (:names) and (t.dz like concat('%',:searchKey,'%') or t.hjdz = :searchKey)") (
建议使用方案2,更加灵活,引入的变量更少。