简体   繁体   中英

Java Spring JPA Repository between date query

Hello I have entity and have createdAt filed specified like this:

@JsonIgnore
@Column(name = "created_at")
@Temporal(TemporalType.TIMESTAMP)
protected Date createdAt;

Every entity includes this field. Now I have complicated SQL query which calculates profit between dates. Query looks like this:

@Query("SELECT SUM(CASE WHEN t.outcome = true THEN - t.amount ELSE t.amount END) as income " +
            "FROM Transaction t " +
            "WHERE t.property = :property " +
            "AND t.createdAt BETWEEN :dateFrom AND :dateTo")
    Double getPropertyProfitBetweenDates(@Param("property")Property property, @Param("dateFrom")Date dateFrom, @Param("dateTo")Date dateTo);

The function that parses dates as I want looks like this:

Calendar start = Calendar.getInstance();
start.add(Calendar.MONTH, -i);
start.set(Calendar.DAY_OF_MONTH, 1);
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);

Calendar end;
end = (Calendar) start.clone();
end.add(Calendar.MONTH, 1);
end.add(Calendar.DAY_OF_MONTH, -1);

Date dateFrom = start.getTime();
Date dateTo = end.getTime();

When I try to access data via repository I call method like this:

transactionService.getPropertyProfitBetweenDates(property, dateFrom, dateTo)

Every time I receive null, but when I mannualy run query in mysql workbench I get correct records. Could you please help me solving this problem out?

I fixed the problem using java.sql.Date

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM