You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot JPA自定义原生查询编译报错问题求助

问题解决:Spring Boot JPA自定义原生查询编译错误

错误原因分析

  1. @Query属性误用:你用了name属性来编写SQL,但name是用来引用预定义命名查询的(比如实体类上@NamedQuery定义的查询名),直接写SQL必须使用value属性。这会导致Spring Data JPA尝试解析方法名生成查询,找不到对应实体属性,从而抛出"No property 'customizedFindUser' found"错误。
  2. 返回值类型错误:List<Optional<UsersEntity>>逻辑不合理,Optional是用来包装单个可能为空的结果,返回集合时,集合本身可以是空的,元素应为实体对象,无需每个都用Optional包裹。
  3. SQL占位符写法问题:%?1%的写法在部分场景下无法被正确解析,容易引发语法错误。

修正后的代码示例

方式一:位置参数绑定

@Query(value = "select * from tblusers where first_name like concat('%', ?1, '%') OR last_name like concat('%', ?2, '%') OR username like concat('%', ?3, '%')", nativeQuery = true)
public List<UsersEntity> customizedFindUser(String firstName, String lastName, String username);

方式二:命名参数绑定(可读性更好)

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

// ...

@Query(value = "select * from tblusers where first_name like concat('%', :firstName, '%') OR last_name like concat('%', :lastName, '%') OR username like concat('%', :username, '%')", nativeQuery = true)
public List<UsersEntity> customizedFindUser(@Param("firstName") String firstName, 
                                            @Param("lastName") String lastName, 
                                            @Param("username") String username);

关键注意点

  • 确保Repository接口继承JpaRepository<UsersEntity, 主键类型>(比如JpaRepository<UsersEntity, Long>)。
  • 数据库表名tblusers和字段名first_name、last_name、username要和实际数据库结构完全匹配。
  • 使用concat拼接通配符和参数,避免直接写%?1%带来的解析问题,同时降低SQL注入风险。

内容的提问来源于stack exchange,提问作者Obert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:50:22