I'm writing complicated queries using Spring data JPA, let's say a statistics query.
@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 in a repository:
@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);
method statAmountByDay
gives me a result like:
[
{"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}
]
but I want statistics by day, only need date, time is useless, expected result:
[
{"time": "2006-01-02", "balance": 300.00}
{"time": "2006-01-03", "balance": 200.00}
]
so I want to know how to convert createdTime
(datetime type) to Date
type, like function DATE(createdTime)
in mysql, but I don't wanna use native query, because my code runs on different ENV, use different databases.
I know it's not the best way to do it, but until I find a better solution, you can manipulate the returned time as a String (using SUBSTRING )
xxx.StatisticsPair(substring(cast(createdTime as nvarchar(19)), 1, 10), sum(amount))
or try:
xxx.StatisticsPair(cast(createdTime as date), sum(amount))
You have two possible solutions:
....
@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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.