JPA的Criteria API

3
我正在尝试在我的Java Web应用程序中实现自定义过滤器。 我想要实现类似于这张照片的功能:enter image description here,但希望设计更好 :))
基本上,我需要使用以下标准来过滤数据: 等于、不等于、类似于、为空、不为空、日期范围内、大于、小于
因此,出于我的目的,我决定使用Criteria API。 我以前从未使用过Criteria API,所以我正在阅读官方文档:https://docs.oracle.com/cd/E19798-01/821-1841/gjixa/index.html 其中有如下代码:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.where(cb.equal(pet.get(Pet_.name), "Fido")
.and(cb.equal(pet.get(Pet_.color), "brown");

我对我的代码进行了修改,现在它是这样的:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Client> cq = cb.createQuery(Client.class);
    Root<Client> client = cq.from(Client.class);
    cq.where(cb.equal(client.get("firstName"), "Fido").and(cb.like(client.get("lastName"), "brown")));
    TypedQuery<Client> q = em.createQuery(cq);
    List<Client> allClients = q.getResultList();

很不幸,我的代码中无法识别.and,编译时会出现错误。

所以我的问题是:

  1. 我选择的数据过滤方法是否正确?
  2. 我的代码有什么问题?

谢谢。

1个回答

2

在你的代码中,你试图使用Predicate对象中不存在的and方法,相反你需要使用如下所示的CriteriaBuilder中的and

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Client> cq = cb.createQuery(Client.class);
        Root<Client> client = cq.from(Client.class);

        //Pass all conditions to CriteriaBuilder 'and'
        Predicate predicate = cb.and(cb.equal(client.get("firstName"), "Fido"),
                   cb.like(client.get("lastName"), "brown")); 
        cq.where(predicate);

        TypedQuery<Client> q = em.createQuery(cq);
        List<Client> allClients = q.getResultList();

此外,您可以参考CriteriaBuilder的其他方法这里

我该如何获取这些结果的计数?我想要创建分页,因此需要获取查询结果的总计数,然后只获取前15条记录。 - Irakli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接