【问题标题】:How get the lastest inserted values with JPA?如何使用 JPA 获取最新插入的值?
【发布时间】:2012-01-18 21:32:58
【问题描述】:

我需要在我的数据库中获取最新插入的“产品”。 我正在使用 JPA (EclipseLink) 来做到这一点,比如:

public List<Product> search(String name){
  // return the lastest results with the maximum of 100 values
}

我该怎么做? 谢谢。

【问题讨论】:

    标签: database jpa jpa-2.0


    【解决方案1】:

    搜索具有给定名称的产品,按插入日期(产品实体中必须存在的列)或按 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();
    

    【讨论】:

      【解决方案2】:

      如果您的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();
      }
      

      【讨论】:

      • 虽然解决方案是对的,但是sn-p的代码看起来像JDO,而不是JPA代码。
      • 哈哈,没错,就是JDO。甚至没有注意到。您的解决方案也是正确的,并且是 JPA。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多