我正在使用带有Hibernate 5.2.1的Java8和带有MySQL的JPA2。
我有以下完美的查询:
final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Rating> criteria = criteriaBuilder.createQuery(Rating.class);
Root<Rating> root = criteria.from(Rating.class);
ParameterExpression<Job> paramJob = criteriaBuilder.parameter(Job.class);
criteria.select(root).where(criteriaBuilder.equal(root.get("job"), paramJob));
如您所见,查询有一个参数paramJob
。我想添加第二个参数:
ParameterExpression<Person> paramPerson = criteriaBuilder.parameter(Person.class);
问题
如何修改以下行以容纳第二个参数?
criteria.select(root).where(criteriaBuilder.equal(root.get("job"), paramJob));
我可以添加第二行:
criteria.select(root).where(criteriaBuilder.equal(root.get("person"), paramPerson));
由于
答案 0 :(得分:6)
试试这个:
criteria.select(root).where(
criteriaBuilder.equal(root.get("job"), paramJob),
criteriaBuilder.equal(root.get("person"), paramPerson)
);
答案 1 :(得分:3)
final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Rating> criteria = criteriaBuilder.createQuery(Rating.class);
Root<Rating> root = criteria.from(Rating.class);
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(criteriaBuilder.equal(root.get("job"), Job.class)); //might need to change ther Person.class to whatever matches the job
predicates.add(criteriaBuilder.equal(root.get("person"), paramPerson)); //same as above
criteria.select(root).where(predicates.toArray(new Predicate[]{}));
//execute query