【发布时间】:2012-01-18 21:32:58
【问题描述】:
我需要在我的数据库中获取最新插入的“产品”。 我正在使用 JPA (EclipseLink) 来做到这一点,比如:
public List<Product> search(String name){
// return the lastest results with the maximum of 100 values
}
我该怎么做? 谢谢。
【问题讨论】:
我需要在我的数据库中获取最新插入的“产品”。 我正在使用 JPA (EclipseLink) 来做到这一点,比如:
public List<Product> search(String name){
// return the lastest results with the maximum of 100 values
}
我该怎么做? 谢谢。
【问题讨论】:
搜索具有给定名称的产品,按插入日期(产品实体中必须存在的列)或按 ID(如果使用序列号作为 ID)按降序排列结果,然后调用 @ 987654321@ 将查询限制为 100 个结果:
TypedQuery<Product> q =
em.createQuery("select p from Product p"
+ " where p.name = :name"
+ " order by p.insertionDate desc", Product.class);
q.setParameter("name", name);
q.setMaxResults(100);
return q.getResultList();
【讨论】:
如果您的Product 类有一个自动递增的“id”字段,您可以这样做。或者,如果该类有一个 createDate 字段,您也可以按该字段排序。
Query q = pm.newQuery(Product.class);
q.setOrdering("id desc");
//q.setOrdering("createDate desc"); //If you have a createDate field
q.setRange(0, 100);
try {
products = (List<Product>)q.execute();
}
finally {
q.closeAll();
}
【讨论】: