使用JPA和@Queries的Spring数据

时间:2018-03-20 11:21:20

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

我有一个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

1 个答案:

答案 0 :(得分:2)

请参阅以下修改后的代码:

方法:

@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]);

希望这会对你有所帮助..