【问题标题】:MySQL LocalDate is being passed as String in JPA Native QueryMySQL LocalDate 在 JPA Native Query 中作为字符串传递
【发布时间】:2019-01-20 23:44:25
【问题描述】:

我在 JPA 本机查询中传递了 LocalDate。但它把它当作字符串并执行。

当我在 MySql Workbench 和 Java 中使用本机查询执行相同的查询时,我得到了不同的结果。

  • 在 MySQL 工作台中:

    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 成为输出。

【问题讨论】:

    标签: java mysql jpa spring-data-jpa mysql-workbench


    【解决方案1】:

    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());
      }
    

    }

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2021-02-15
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多