使用JPA @Query注解查询数据时遭遇Column 'id' not found错误求助
解决JPA原生查询报错Column 'id' not found的问题
问题原因
你的原生查询仅返回name和score字段,但方法声明返回List<UserResult>。由于UserResult实体包含id字段(从CrudRepository<UserResult, String>的泛型参数可推断),JPA在映射查询结果时找不到id列,因此抛出java.sql.SQLException: Column 'id' not found错误。
解决方案
1. 查询所有实体必需字段
如果需要完整的UserResult实体,修改查询语句包含id字段:
public interface UserResultRepository extends CrudRepository<UserResult, String> { @Query(value = "SELECT id, name, score FROM quizzapp.user_result result WHERE result.quiz_id = :quizId", nativeQuery = true) List<UserResult> listResultsForExport(@Param("quizId") String quizId); }
2. 使用DTO接收部分字段
若仅需name和score,创建专用DTO类:
// 定义DTO类 public class UserResultExportDTO { private String name; private Integer score; // 构造方法参数顺序需与查询字段顺序一致 public UserResultExportDTO(String name, Integer score) { this.name = name; this.score = score; } // 提供getter方法 public String getName() { return name; } public Integer getScore() { return score; } }
修改Repository方法返回DTO列表:
public interface UserResultRepository extends CrudRepository<UserResult, String> { @Query(value = "SELECT name, score FROM quizzapp.user_result result WHERE result.quiz_id = :quizId", nativeQuery = true) List<UserResultExportDTO> listResultsForExport(@Param("quizId") String quizId); }
如果想用JPQL而非原生查询,可直接调用DTO构造方法,无需转换器:
@Query("SELECT new com.yourpackage.UserResultExportDTO(u.name, u.score) FROM UserResult u WHERE u.quizId = :quizId") List<UserResultExportDTO> listResultsForExport(@Param("quizId") String quizId);
3. 使用接口投影
通过定义投影接口简化部分字段查询,无需创建DTO类:
// 定义投影接口 public interface UserResultProjection { String getName(); Integer getScore(); }
修改Repository方法返回投影接口列表:
public interface UserResultRepository extends CrudRepository<UserResult, String> { @Query(value = "SELECT name, score FROM quizzapp.user_result result WHERE result.quiz_id = :quizId", nativeQuery = true) List<UserResultProjection> listResultsForExport(@Param("quizId") String quizId); }
内容的提问来源于stack exchange,提问作者Pedro Hugo
相关产品推荐
相关产品推荐

