5

My understanding is that the Hibernate Criteria API is deprecated:

As of Hibernate 5.2, the JPA Criteria API should be used instead

But in Hibernate Criteria API, building complex queries with JOINs was easy. I could do it as follows:

Criteria criteriaQuery = session.createCriteria(Request.class);
// 1. Prepare aliases (JOINs) from main table
if (!StringUtils.isBlank(searchCriteria.getRequestorName())) {
    criteriaQuery.createAlias("requestor", "npRequestor", JoinType.INNER_JOIN);
}
if (!StringUtils.isBlank(searchCriteria.getApproverName())) {
    criteriaQuery.createAlias("workflows", "wf", JoinType.INNER_JOIN);
    criteriaQuery.createAlias("wf.approver", "npApprover", JoinType.INNER_JOIN);
}
// Prepare criteria
// ...
criteriaQuery.add(Restrictions.eq("wf.someAttribute", someAttr));
}       

But doing JOINs and complex queries in JPA Criteria API is extremely difficult. As one user noted in this thread, "I'm having a hard time creating complex joins using Criteria API and not finding extensive documentation and examples."

A simple Join requires the creation of a Metamodel (a separate process), then an EntityType, and the syntax is hard to construct. The below is just the simplest example possible, but I have multiple If/Else conditions and multi-way Joins.

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
EntityType<Owner> Owner_ = m.entity(Owner.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);

Why are people shooting themselves in the foot? Why deprecate something perfectly usable in favor of an unwieldy and hard-to-use alternative?

gene b.
  • 10,512
  • 21
  • 115
  • 227

0 Answers0