我有以下情况3表,人,工作,类别。 人有工作,工作有一个类别。如何从同一类别中获取人员记录。
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..
}
答案 0 :(得分:1)
使用JPQL查询很容易做到
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();
一些假设:
job
category
答案 1 :(得分:0)
尚未测试,但可能类似
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;
答案 2 :(得分:0)
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();
答案 3 :(得分:0)
我的版本是:
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();
在这里,Person
one-to-one
为Job
,后者为one-to-one
Category
:)您将收到所有人指定的工作类别。