![](/img/trans.png)
[英]How to concatenate DATE and TIME to form DATETIME (TIMESTAMP) in a JPA query?
[英]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))
您有兩種可能的解決方案:
....
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StatisticsPair {
private LocalDate date;
private BigDecimal balance;
}
....
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.