背景
java.lang.ClassCastException: class java.math.BigDecimal cannot be cast to class java.lang.Integer (java.math.BigDecimal and java.lang.Integer are in module java.base of loader 'bootstrap') 报错### 问题分析
当使用JPA投影查询时,若数据库字段类型为DECIMAL/NUMERIC(映射为BigDecimal),但试图强制转换为Integer,会触发ClassCastException。以下是解决方案和示例。
解决方案:修改投影接口字段类型
确保投影接口的返回类型与数据库字段类型匹配:
public class ProductDTO {
private String name;
private Integer price;
public ProductDTO(String name, Integer price) {
this.name = name;
this.price = price;
}
// Getters
}
Repository查询
@Query("SELECT (p.name, p.price FROM product p",nativeQuery = true)
List<ProductDTO> findProductDTOs();