Spring Data Jpa 使用的hibernate 不支持 日期函数 to_char 的解决方案

2022年6月24日12:14:20

今天在公司折腾了一天,写的心急火燎的,也弄得心情特别不好,因为老板就坐我的对面,就因为to_char-----> to_char(date,‘YYYY-MM’)这个数据库函数在hibernate 中不能使用,但是在实际的业务中又是需要的,所以,没办法,我就各种google 和baidu,搜了一下午,都没有好的解决方案,因为得到的结论都是一样的,to_char() 这个数据库函数不能在hibernate中使用,晚上,吃饱了,无意中翻到了   以下的两个地址   http://bbs.csdn.net/wap/topics/390051012   ,http://blog.csdn.net/chenhuade85/article/details/7572148,  尤其是后面的这个地址 , 文中分析的很到位,也更加更深刻的理解了hibernate.

因为也看到了 可以使用year 和 month ,所以我就想到能不能通过分别查出来 他们的月份和年份,通过DTO 返回后,到前端】重新组合。实验了一下,果然可以。

DTO:

@Data@AllArgsConstructor@NoArgsConstructorpublic classStockInDTO {
    Stringsupplier;
    Longcount;intyear;intmonth;
}

实体类:

@Entity@Table(name="stockins")@Data@ApiModel(value ="StockIn", description ="入库表")public classStockInextendsAbstractAuditing {@Id    @ApiModelProperty(value ="入库ID=订单ID", readOnly =true)privateStringid;@ApiModelProperty(value ="提货商")privateStringsupplier;@ApiModelProperty(value ="车辆批次/提货次数")privateStringsupplierIndex;@ApiModelProperty(value ="提货备注")privateStringsupplierComment;@ApiModelProperty(value ="入库时间", hidden =true)privateDatestockInAt;

模拟数据内容:

insert intostockins(id, stockInAt,  supplier, supplierIndex, supplierComment)values('Command1-001','2017-01-01 00:00:00',NULL,NULL,NULL),
       ('Command1-002','2017-01-01 00:00:00',NULL,NULL,NULL),
       ('Command1-003','2017-02-01 00:00:00','CBF','3','提货'),
       ('Command1-004','2017-02-02 00:00:00','CBF','3','提货'),
       ('Command1-005','2017-03-01 00:00:00',NULL,NULL,NULL),
       ('Command3-000','2017-11-01 00:00:00',NULL,NULL,NULL),
       ('Command3-001','2017-12-01 00:00:00','CBF','2','提货');

接下来是重点:

@Repository
public interface StockInRepository extends
    PagingAndSortingRepository<StockIn, String>,
    JpaSpecificationExecutor<StockIn> {
 
    @Query(value = "SELECT new com.yangnaihua123.domain.vm.StockInDTO(c.supplier, count(c.supplierIndex), year(c.stockInAt), month(c.stockInAt)) from StockIn c WHERE c.supplier <> null group by supplier, year(stockInAt), month(stockInAt)")
// 以上的代码用到了进行年份和月份的分组
    List<StockInDTO> findStockInCount();
}

所以通过List<StockInDTO> 往前端传输DTO,拿到了year和month 进行拼接就好了。

不容易

  • 作者:petitpaul
  • 原文链接:https://blog.csdn.net/yangnaihua123/article/details/79212651
    更新时间:2022年6月24日12:14:20 ,共 1900 字。