SpringBoot Repository实现Distinct查询遇500错误求助
问题:根据指定字段获取另一字段去重值时出现500错误
我需要在Service层实现方法,调用Repository从内存数据库根据指定字段获取另一字段的去重值,当前代码调用API时返回500内部服务器错误,以下是我的实现:
Controller层代码
@GetMapping(value="filters") public List<String> getFilterId(){ return filterService.getFilterIdByReportType(ReportType.TIMESHEET); }
Service层代码
public List<String> getFilterIdByReportType(ReportType reportType) { return filterRepository.findDistinctFiltersByReportType(ReportType.TIMESHEET); }
Repository层代码
@Repository public interface FilterRepository extends JpaRepository<Filters, Long> { @Query(value = "select DISTINCT FILTER_ID from FILTERS where REPORT_TYPE IN (:reportType)", nativeQuery = true) List<String> findDistinctFiltersByReportType(ReportType reportType); }
数据库表结构
| ID | REPORT_TYPE | FILTER_ID | DISPLAY_VALUE | FILTER_TYPE | POSSIBLE_VALUES |
|---|---|---|---|---|---|
| 1 | A | organization | Organization | combo_box | ABC |
| 2 | A | country | Country | combo_box | XYZ |
| 3 | A | name | Name | combo_box | PQR |
期望结果
返回去重后的FILTER_ID列表:
organization country name
问题排查与修复方案
1. Service层参数硬编码错误
Service方法接收了reportType参数,但调用Repository时直接写死了ReportType.TIMESHEET,应该传递方法参数:
public List<String> getFilterIdByReportType(ReportType reportType) { return filterRepository.findDistinctFiltersByReportType(reportType); }
2. 原生查询中枚举参数的类型不匹配问题
ReportType是枚举类型,原生查询中直接使用IN (:reportType)会导致参数类型不匹配——枚举默认传递的是对象而非数据库存储的字符串值(比如表中存储的"A")。
单值匹配场景修改方案:
调整Repository查询语句,将参数改为字符串类型,并指定参数名:@Query(value = "select DISTINCT FILTER_ID from FILTERS where REPORT_TYPE = :reportType", nativeQuery = true) List<String> findDistinctFiltersByReportType(@Param("reportType") String reportType);Service层调用时传递枚举的字符串值:
return filterRepository.findDistinctFiltersByReportType(reportType.name());多值匹配场景修改方案:
如果需要支持传入多个枚举值,调整查询和参数传递方式:@Query(value = "select DISTINCT FILTER_ID from FILTERS where REPORT_TYPE IN (:reportTypes)", nativeQuery = true) List<String> findDistinctFiltersByReportType(@Param("reportTypes") List<String> reportTypes);Service层调用时将枚举转为字符串列表:
return filterRepository.findDistinctFiltersByReportType(Collections.singletonList(reportType.name()));
3. 枚举与数据库字段映射验证
确保ReportType枚举的name()值,或者通过@Enumerated(EnumType.STRING)注解配置的存储值,与数据库中REPORT_TYPE字段的实际存储值一致。
4. 日志辅助排查
开启Spring Boot SQL日志,查看实际执行的SQL语句和参数:
在application.properties中添加配置:
logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
通过日志确认参数是否正确传递,SQL语句是否符合预期。
内容的提问来源于stack exchange,提问作者RuchiG
相关产品推荐
相关产品推荐

