Hibernate CriteriaBuilder有两个参数

时间:2017-05-26 08:42:10

标签: java sql hibernate jpa jpa-2.0

我正在使用带有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));

由于

2 个答案:

答案 0 :(得分:6)

试试这个:

criteria.select(root).where(
    criteriaBuilder.equal(root.get("job"), paramJob),
    criteriaBuilder.equal(root.get("person"), paramPerson)
);

答案 1 :(得分:3)

在我眼里,这是一种更有活力的方法。你将不得不调整一些东西,但这样你也可以设置一个动态的where子句:

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