Spring Data JPA-从本机查询返回到POJO的Map对象

时间:2018-10-22 09:07:47

标签: java spring hibernate jpa spring-data-jpa

我有一种情况,我想将从JPA存储库中的本机查询中获取的数据映射到自定义对象。

我的存储库代码如下:

@Query(nativeQuery = true,name = "TopCouponOffer")
List<TopCouponOffer> findTodayTopOffer(@Param("date") String date, @Param("time") String time);

我的自定义类代码如下:

@NamedNativeQuery(
    name = "TopCouponOffer",
    query =
           "SELECT c.id,c.code\n" +
                   " FROM COUPON c \n" +
                   "JOIN CLICK cl\n" +
                   "ON cl.coupon_id = c.id\n" +
                   "JOIN COUPONS_STATUS cs\n" +
                   "ON cs.id= c.coupons_status_id\n" +
                   "JOIN COUPONS_OFFER_TYPE ct\n" +
                   " ON ct.id= c.coupons_offer_types_id\n" +
                   "WHERE\n" +
                   " c.ongoing_offer = 1 AND\n" +
                   " c.coupons_status_id != 4 AND\n" +
                   "IF(:date < c.end_date,\n" +
                   "             IF(:date < c.start_date,\n" +
                   "                 0,\n" +
                   "                 IF(:date = c.start_date,\n" +
                   "                     IF(:time < c.start_time,\n" +
                   "                         0,\n" +
                   "                         1),\n" +
                   "                     1)),\n" +
                   "             IF(:date = c.end_date || :date = c.start_date, \n" +
                   "                IF(:time > c.end_time || :time < c.start_time,\n" +
                   "                         0,\n" +
                   "                         1), 0)) = 1 ORDER BY cl.count DESC LIMIT 2",
    resultSetMapping = "TopCouponOffer",
    resultClass = TopCouponOffer.class
)
@SqlResultSetMapping(name="TopCouponOffer",
        classes = {
        @ConstructorResult(targetClass = TopCouponOffer.class,columns = {
                @ColumnResult(name = "id"),
                @ColumnResult(name = "code")
        })
        }
)
public class TopCouponOffer {
    Integer id;
    String code;
    public TopCouponOffer(Integer id, String code){
       this.id=id;
       this.code=code;
   }
}

但是运行应用程序时出现以下错误

  

由以下原因引起:org.springframework.data.mapping.PropertyReferenceException:没有为Coupon类型找到属性findTodayTopOffer!

我应该将名称查询和sqlresultmapping移到我的实体类吗?问题是我不想污染我的实体类,是否可以通过向我的实体类添加更多代码来实现这一目标?

1 个答案:

答案 0 :(得分:0)

我相信您在存储库中的函数名称应重命名为findByDateAndTime。