【问题标题】:Spring Data with JPA and @Queries使用 JPA 和 @Queries 的 Spring Data
【发布时间】:2018-03-20 11:21:20
【问题描述】:

我有一个 SpringBoot 应用程序和一个从 PagingAndSortingRepository 扩展的界面

用这个方法

@Query(value = "select cp.price, cp.update_date from t_hotel_price cp where cp.hotel_id = ?1 and cp.update_date between ?2 and NOW() order by cp.price ASC LIMIT 1", nativeQuery = true)
Object[] getMaxPriceAndDate (Long hotelId, Date aggregationDate);

来自 JunitTests

Object[] priceAndDate = hotelPriceService.getMaxPriceAndDate(currency.getId(),DateUtils.weeklyDate());  

        System.out.println 
            (priceAndDate[0]);

        System.out.println 
            (priceAndDate[1]);

期望 priceAndDate[0] 中的价格和 priceAndDate[1] 中的日期

但是我得到了一个java.lang.ArrayIndexOutOfBoundsException: 1

【问题讨论】:

  • 如果您调试该代码会发生什么?你能转储priceAndDate 看看它包含什么吗?

标签: mysql sql spring-boot spring-data spring-data-jpa


【解决方案1】:

请看下面的修改代码:

方法:

@Query(value = "select cp.price, cp.update_date from t_hotel_price cp where cp.hotel_id = ?1 and cp.update_date between ?2 and NOW() order by cp.price ASC LIMIT 1", nativeQuery = true)
List<Object> getMaxPriceAndDate (Long hotelId, Date aggregationDate);

JunitTests:

List<Object> priceAndDates = hotelPriceService.getMaxPriceAndDate(currency.getId(),DateUtils.weeklyDate());  
Object[] priceAndDate = (Object[])priceAndDates.get(0);

        System.out.println 
            (priceAndDate[0]);
        System.out.println 
            (priceAndDate[1]);

希望对你有帮助..

【讨论】:

  • 在获取 priceAndDates.get(0) 之前,添加检查 priceAndDates.size() > 0。而不是强制转换为 Object[] 或使用 List,你最好有一个模型类,具有适当的类型安全性,例如 List.
猜你喜欢
  • 2017-11-29
  • 2016-06-22
  • 2017-09-29
  • 1970-01-01
  • 2015-11-03
  • 2012-11-09
  • 2019-07-20
  • 2016-02-12
  • 1970-01-01
相关资源
最近更新 更多