如何按子句条件查询进行排序

时间:2015-03-27 12:51:52

标签: java-ee jpa criteria

这是我的代码:

       public List<Veiculo> getAll()
   {

      CriteriaQuery<Veiculo> criteria = this.entityManager
            .getCriteriaBuilder().createQuery(Veiculo.class);
      return this.entityManager.createQuery(  
            criteria.select(criteria.from(Veiculo.class))).getResultList();
   }

现在,我需要一个order by子句来查询条件。

orderby veiculo.getServico

我尝试,但不工作

   public List<Veiculo> getAll()
   {

      CriteriaQuery<Veiculo> criteria = this.entityManager
            .getCriteriaBuilder().createQuery(Veiculo.class);
      return this.entityManager.createQuery(  
            criteria.select(criteria.from(Veiculo.class)).orderBy(getVeiculo().getServico())).getResultList();
   }

1 个答案:

答案 0 :(得分:4)

重写之后应该适合你,没有编译,所以考虑作为示例性元代码

    CriteriaBuilder cb = this.entityManager
                .getCriteriaBuilder();
    CriteriaQuery<Veiculo> criteria = cb.createQuery(Veiculo.class);
    Root<Veiculo> root = criteria.from(Veiculo.class);
    return this.entityManager.createQuery(
                 criteria.select(root).orderBy(cb.asc(root.get("servico"))))
           .getResultList();