我在JPA本机查询中传递了LocalDate。但是它将其作为String并执行。
当我在MySql Workbench中执行相同的查询时,以及使用本机查询从Java中执行相同的查询时,都会得到不同的结果。
在MySQL Workbench中:
select sum(expense_amount) from budgetreferee.br_expense
where household_id=1 and next_due_date between 2018-08-01 and 2019-07-31
and category_id IN(41,51,58,70,74,83,94,2,20,10,9,22,28) OR
is_bill=TRUE and expense_id IS NOT NULL;
结果是:58171.00
使用本机查询:
@Query(value = "select sum(expense_amount) from br_expense where household_id=:householdId and next_due_date between str_to_date(:startDate,'%Y-%m-%d') and str_to_date(:endDate,'%Y-%m-%d') and category_id IN(41,51,58,70,74,83,94,2,20,10,9,22,28) OR is_bill=TRUE and expense_id IS NOT NULL;",nativeQuery = true)
BigDecimal getTotalExpenseAmount(@Param("householdId") Long householdId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate)
这将导致以下查询:
select sum(expense_amount) from budgetreferee.br_expense
where household_id=1 and next_due_date between str_to_date
('2018-08-01','%Y- %m-%d')
and str_to_date('2019-07-31','%Y-%m-%d') and
category_id IN(41,51,58,70,74,83,94,2,20,10,9,22,28) OR is_bill=TRUE
and expense_id IS NOT NULL;
结果为109871.00
如何解决此差异? 从Java执行时,我希望将58171.00作为输出。
答案 0 :(得分:0)
JPA 2.1在Java 8之前发布,这就是默认情况下不支持LocalDate的原因。您可以使用Converter
为您完成这项工作。
import java.sql.Date;
import java.time.LocalDate;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate localDate) {
return (localDate == null ? null : Date.valueOf(localDate));
}
@Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}