SpringBoot JPA执行原生分页查询报limit附近SQL语法错误求助
问题现象
执行JPA原生分页查询时抛出SQL语法异常,错误信息如下:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'limit 5' at line 1.
报错对应的Repository实现代码:
@Repository public interface AdherentRepository extends JpaRepository<Adherent, Long> { public Iterable<Adherent> findByEmpruntsIdemprunt(Long Id); @Query(value = "SELECT * FROM adherent WHERE nom LIKE :x OR email LIKE :x OR matricule LIKE :x ;", nativeQuery = true) public Page<Adherent> findAdherent(@Param("x") String x, Pageable pageable); }
该方法预期实现对nom、email、matricule三个字段的模糊匹配,传入Pageable参数执行分页时触发上述错误,错误指向limit 5附近语法异常。
错误根因
- 自定义原生SQL末尾多余的分号
;是触发报错的直接原因。Spring Data JPA 处理原生分页查询时,会自动在开发者编写的SQL语句末尾拼接LIMIT 页大小 OFFSET 偏移量的分页语法,末尾的分号会将SQL截断,最终执行的SQL结构为SELECT * FROM adherent ... ; limit 5,分号后的limit语句没有依附的有效查询主体,直接触发语法错误。 - 现有LIKE写法存在逻辑缺陷:如果传入的参数
x没有手动拼接%通配符,LIKE查询会退化为精确匹配,无法实现预期的模糊搜索效果。
修复方法
- 删除自定义SQL语句末尾的分号,保证JPA可以正常拼接分页参数
- 调整LIKE匹配逻辑,通过
CONCAT函数自动拼接通配符,无需在调用层手动处理参数
修复后的代码如下:
@Repository public interface AdherentRepository extends JpaRepository<Adherent, Long> { Iterable<Adherent> findByEmpruntsIdemprunt(Long Id); @Query(value = "SELECT * FROM adherent WHERE nom LIKE CONCAT('%', :x, '%') OR email LIKE CONCAT('%', :x, '%') OR matricule LIKE CONCAT('%', :x, '%')", nativeQuery = true) Page<Adherent> findAdherent(@Param("x") String x, Pageable pageable); }
内容的提问来源于stack exchange,提问作者BTF
相关产品推荐
相关产品推荐

