如何将sql原生查询结果映射到春季jpa存储库中的DTO中?
2022-09-03 16:40:40
嗨,我试图实现的是将SQL本机查询结果映射到Java Spring jpa存储库中的DTO中,我如何正确地做到这一点?我尝试了几个代码,但它不起作用,这是我尝试过的:
第一次尝试 :
@Repository
public interface StockRepository extends RevisionRepository<Stock, Long, Integer>, JpaRepository<Stock, Long> {
@Query(value = "SELECT stock_akhir.product_id AS productId, stock_akhir.product_code AS productCode, SUM(stock_akhir.qty) as stockAkhir "
+ "FROM book_stock stock_akhir "
+ "where warehouse_code = (:warehouseCode) "
+ "AND product_code IN (:productCodes) "
+ "GROUP BY product_id, product_code, warehouse_id, warehouse_code", nativeQuery = true)
List<StockAkhirDto> findStockAkhirPerProductIn(@Param("warehouseCode") String warehouseCode, @Param("productCodes") Set<String> productCode);
}
执行函数后,我得到这个错误:
找不到能够从类型 [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] 转换为类型 [com.b2bwarehouse.Dto.RequestDto.StockDto.StockAkhirDto] 的转换器
第二次尝试 :
@Repository
public interface StockRepository extends RevisionRepository<Stock, Long, Integer>, JpaRepository<Stock, Long> {
@Query(value = "SELECT new com.b2bwarehouse.Dto.RequestDto.StockDto.StockAkhirDto(stock_akhir.product_id AS productId, stock_akhir.product_code AS productCode, SUM(stock_akhir.qty) as stockAkhir) "
+ "FROM book_stock stock_akhir "
+ "where warehouse_code = (:warehouseCode) "
+ "AND product_code IN (:productCodes) "
+ "GROUP BY product_id, product_code, warehouse_id, warehouse_code", nativeQuery = true)
List<StockAkhirDto> findStockAkhirPerProductIn(@Param("warehouseCode") String warehouseCode, @Param("productCodes") Set<String> productCode);
}
第二个是错误:
无法提取结果集;SQL [n/a];嵌套异常是 org.hibernate.exception.SQLGrammarException: 无法提取 ResultSet
以下是我的DTO:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StockAkhirDto {
private Long productId;
private String productCode;
private Integer stockAkhir;
}
我应该如何更正我的代码?那么,我可以将结果输入到我的 DTO 中吗?