Question

I have the following situation 3 tables, person, job, category. Person has a job and Job has a category. How do I get the person records from the same category.

 public List<Person> findPplByCategory(Category category) {
    javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<Person> e = cq.from(Person.class);
    javax.persistence.criteria.Root<Job> a = cq.from(Job.class);
    //...not sure how to create the query here..
}
Was it helpful?

Solution 3

    javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<Person> e = cq.from(perdon.class);
    cq.where(cb.equal(e.get("idCompany").get("idCategory"), cat));
    cq.orderBy(cb.desc(e.get("idPerson")));
    return getEntityManager().createQuery(cq).getResultList();

OTHER TIPS

This is easy to do using a JPQL query

String query = "select P from Person P join P.job J join J.category C where C = :cat"

List<Person> = entitiyManager.createQuery(query, Person.class).setParameter("cat", myCategory).getResultList();

Some assumptions:

  • One Person has one Job
  • One Job has one Category
  • Person's job field is named job
  • Job's category field is named category

haven't tested but may be something like

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Person> q = cb.createQuery(Person.class);
    Root<Person> person = q.from(Person.class);
    Join<Person,Job> job = person.join(Person_.job);

    Predicate predicate = cb.conjunction();
    Predicate p = cb.equal(job.get(Job_.category), cat);
    predicate = cb.and(p);

    q.where(predicate);
    q.select(person);

    TypedQuery<Person> tq = entityManager.createQuery(q);
    List<Person> all = tq.getResultList();

    return all;

my version is:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);
Join<Person,Job> job = root.join(Person_.job);
Join<Job,Category> category =car.join(Car_.category).where(cb.equal(job.get(Job_.category).get(Category_.name),"your category"));
cq.select(root);
TypedQuery<Person> query = getEntityManager().createQuery(cq);
return query.getResultList();

Here you have that Person is one-to-one with Job and the latter is one-to-one with Category :) You will receive you all persons which is in specified category of job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top