【发布时间】:2011-01-20 08:30:08
【问题描述】:
我有两个实体:
Items(id, user_id, title, price);
Purchases(id, item_id, user_id, date);
使用 JPA,我想列出购买次数超过 X 次的所有商品,按购买次数排序(第一个是购买次数最多的商品)。
我设法获得了正确的 SQL 请求,但我如何在 JPA 中做到这一点(可能不使用 createQuery 或类似的东西):
SELECT i.title, COUNT(p.id) as rank FROM items AS i LEFT OUTER JOIN purchases AS p ON p.item_id = i.id WHERE rank > X GROUP BY i.title ORDER BY rank DESC;
// of course, X is an int!
感谢您的帮助! :)
更新: 我表示要避免 createQuery,但我没有解释原因。 问题是,我创建了一个专门用于生成查询的类,它看起来像:
public class Arguments {
protected HashSet allowedOrders = new HashSet();
protected Collection args = new ArrayList();
// constructor and some other methods
// this one works great
public void setPriceMin(int price) {
query += " AND price > ?";
args.put(price);
}
// sames method for setPrice (= ?), and setPriceMax (= <)
// this one doesn't :/
public void setSalesMin(int sales) {
// here's my problem
}
}
但是(真的)有可能我的方法不好。既然你提出了标准,也许我应该看看它,即使是“setPriceMin”和所有其他方法。
你好吗?
【问题讨论】:
-
请在 SQL 中显示您想要的内容。
-
为什么要避免 createQuery()?通过 Criteria API(如果您使用 JPA2)或通过直接 JPA Query(命名查询),JPA 查询是一种方式。你真的在你的购买实体中存储了 item_id 吗? JPA 的方式是引用该项目并让 JPA 处理 ID 内容。
-
@bert no no 我没有将 item_id 存储在购买中,它在我的数据库中,我有 item_id