簡體   English   中英

如何在JPA查詢中將Datetime轉換為Date

[英]How to convert Datetime to Date in JPA query

我正在使用Spring數據JPA編寫復雜的查詢,比如說統計查詢。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StatisticsPair {
  private LocalDateTime time;
  private BigDecimal balance;
}

@Data
@Entity
@Table(name="t_order")
public class Order {
  private LocalDateTime createdTime;
  private BigDecimal amount;
  private OrderStatus status;
}

在存儲庫中查詢:

@Query("select new xxx.StatisticsPair(createdTime, sum(amount)) from Order where createdTime >= ?1 and createdTime <= ?2 and status = xxx.OrderStatus.COMPLETED group by createdTime")
List<StatisticsPair> statAmountByDay(LocalDateTime from, LocalDateTime to);

statAmountByDay方法給我的結果是:

[
  {"time": "2006-01-02 15:04:05", "balance": 100.00}
  {"time": "2006-01-02 16:04:05", "balance": 200.00}
  {"time": "2006-01-03 15:04:05", "balance": 200.00}
]

但是我想按天統計,只需要日期,時間就沒用了,預期結果:

[
  {"time": "2006-01-02", "balance": 300.00}
  {"time": "2006-01-03", "balance": 200.00}
]

所以我想知道如何將createdTime (日期時間類型)轉換為Date類型,就像mysql中的函數DATE(createdTime)一樣,但是我不想使用本機查詢,因為我的代碼在不同的ENV上運行,並且使用不同的數據庫。

我知道這不是最好的方法,但是在找到更好的解決方案之前,您可以將返回的時間作為String進行操作(使用SUBSTRING

xxx.StatisticsPair(substring(cast(createdTime as nvarchar(19)), 1, 10), sum(amount))

或嘗試:

xxx.StatisticsPair(cast(createdTime as date), sum(amount))

您有兩種可能的解決方案:

  1. 將對象StatisticsPair中的LocalDateTime更改為LocalDate而不是LocalDateTime,並希望spring JPA僅采用日期部分:

....

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StatisticsPair {
    private LocalDate date;
    private BigDecimal balance;
}
  1. 第二種解決方案是在StatisticsPair列表上使用java和java流進行操作:

....

List<StatisticsPair> list = ... ;
List<StatisticsPairWithDate> listWithDate;
listWithDate = list
            .stream()
            .map(sp-> 
                    new StatisticsPairWithDate(
                            sp.getTime().toLocalDate(), 
                            sp.getBalance()))
            .collect(Collectors.toList()); 

....

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StatisticsPairWithDate {
  private LocalDate date;
  private BigDecimal balance;
}

=============================================

@Query("select new xxx.StatisticsPair(createdTime, sum(amount)) from Order where createdTime >= ?1 and createdTime <= ?2 and status = xxx.OrderStatus.COMPLETED group by createdTime")
List<StatisticsPair> statAmountByDay(LocalDate from, LocalDate to);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM