Irakli
Irakli

Reputation: 983

Criteria API JPA

I'm trying to implement custom filter in my Java web application. I want to achieve something like this photo:

enter image description here

but with better design :))

Basically I will need to Filter data using criterias like: equal, not equal, like, is empty,not empty, between(Dates), more than, less then

So for my reason I decided to use Criteria API. I have never used criteria API before so I'm reading the official documentation:

https://docs.oracle.com/cd/E19798-01/821-1841/gjixa/index.html

There is code like this :

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");

I have made changes to my code and it looks like this:

    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();

but unfortunately .and is not recognised in my code and compilation throws error.

So my questions are:

  1. Have I chosen the right method for filtering data
  2. what is wrong with my code?

Thanks

Upvotes: 3

Views: 441

Answers (1)

Vasu
Vasu

Reputation: 22452

In your code, you are trying to use and method from Predicate object which does not exist, rather you need to use and with CriteriaBuilder as shown below:

        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();

Also, you can refer the other methods of CriteriaBuilder here.

Upvotes: 2

Related Questions