【发布时间】:2015-11-02 13:04:08
【问题描述】:
我在针对我的 MySQL 表编写 JPA 查询时遇到问题。
表结构如下:
mysql> desc t_product_purchase;
+-----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| oid | bigint(20) | NO | PRI | NULL | |
| consumer_id | bigint(20) | NO | | NULL | |
| number | bigint(20) | YES | | NULL | |
| pay_time | datetime | YES | | NULL | |
| payment | float | YES | | NULL | |
| price | float | YES | | NULL | |
| product_num_iid | bigint(20) | NO | | NULL | |
| seller_id | bigint(20) | NO | MUL | NULL | |
| product_title | varchar(255) | YES | | NULL | |
+-----------------+--------------+------+-----+---------+-------+
9 rows in set (0.00 sec)
以下 SQL 已按预期执行。
select m.product_num_iid, sum(m.payment) as payment, sum(m.number) as nbr from t_product_purchase m where m.seller_id = 247475251 and m.pay_time >= 0 group by m.product_num_iid order by payment desc limit 0, 10
付款可以正确下单。
在我的 spring-boot JPA 存储库界面中: @Transactional @Repository 公共接口 ProductPurchaseMeasurementRepository 扩展 JpaRepository {
@Query(value = "select m.product_num_iid, sum(m.payment) as payment, sum(m.number) as nbr from t_product_purchase m where m.seller_id = ?1 and m.pay_time >= ?2 and m.pay_time < ?3 group by m.product_num_iid order by ?4 desc limit ?5, ?6", nativeQuery = true)
public List findRankedProductPaymentOrCountBySellerIdWithinPayTime(long sellerId, Date startPayTime, Date endPayTime, String orderBy, long offset, long size);
}
参数 orderBy 将传递值“payment”。但是我无法在方法的返回值中得到有序的记录。
有人知道为什么存储库方法没有按预期工作吗?谢谢。
【问题讨论】:
-
启用显示sql并检查发送到数据库的查询
-
ORDER BY ?4中的占位符被解释为文字,而不是列名,这就是它不起作用的原因。有关详细信息,请参阅this post。 -
@BohuslavBurghardt - 谢谢。你提供的帖子真的很有帮助。我会试验一下。