Spring Data JPA报错:Column 'id' not found 问题求助
解决JPA原生查询返回List时提示"Column 'id' not found"的问题
嘿,我一眼就看出问题出在哪了!你在CarRepository里写的getAllMakes方法犯了一个典型的JPA映射错误:
你用原生SQL只查询了make列,但方法返回的是List<Car>——JPA/Hibernate在拿到查询结果后,会尝试把每条结果映射成一个完整的Car实体对象。但Car实体需要id、model、year这些字段才能实例化,你的SQL里根本没返回这些字段,所以Hibernate就会报错说找不到id列。
下面给你两种解决方案,看你实际需求选:
方案一:只获取汽车品牌(make)的字符串列表
如果你确实只需要所有的品牌名称,那直接把返回类型改成List<String>就好,没必要返回完整的Car对象:
1. 修改CarRepository
package com.example.demo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface CarRepository extends JpaRepository<Car, String> { @Query(value="SELECT make FROM car", nativeQuery=true) List<String> getAllMakes(); // 这里把返回类型从List<Car>改成List<String> }
2. 修改CarController的list接口
@GetMapping("/list") public String carMakeList(Model model){ model.addAttribute("makeList", carRepository.getAllMakes()); // 把属性名改成更贴合的makeList return "list"; }
3. 调整list.html页面
现在页面遍历的是字符串列表,所以要修改表格结构和判断逻辑:
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Car Makes</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <h1>Car Make List</h1> <table> <thead> <tr> <th>Make</th> </tr> </thead> <tbody> <tr th:if="${makeList.isEmpty()}"> <td colspan="1"> No Car Makes Available</td> </tr> <tr th:each="make : ${makeList}"> <td><span th:text="${make}">Make</span></td> </tr> </tbody> </table> </body> </html>
方案二:返回完整的Car实体列表(只在页面展示make)
如果你的实际需求是要获取完整的汽车数据,只是页面上只展示品牌,那应该查询整个Car实体,而不是只查make列:
1. 修改CarRepository
你可以直接用Spring Data JPA提供的默认方法,或者修正原生查询:
public interface CarRepository extends JpaRepository<Car, String> { // 方法1:用Spring Data JPA的默认findAll方法,不需要自己写Query // List<Car> findAll(); // 方法2:如果一定要用原生查询,查询所有字段 @Query(value="SELECT * FROM car", nativeQuery=true) List<Car> getAllMakes(); }
2. 修正list.html的判断逻辑
原来的th:if="${!list}"判断是错误的,应该判断列表是否为空:
<tr th:if="${list.isEmpty()}"> <td colspan="4"> No Cars Available</td> </tr>
这样修改后,Hibernate能拿到完整的Car实体数据,就不会再报找不到id列的错误了,页面上依然可以只展示make字段。
内容的提问来源于stack exchange,提问作者wallwalker
相关产品推荐
相关产品推荐

