Hibernate – Rewrites the legacy createCriteria
I have the following Hibernate code:
return (Post)sessionFactory.getCurrentSession()
.createCriteria(Post.class)
.add(Restrictions.eq("title", title))
.add(Restrictions.eq("description", description))
.uniqueResult();
However, the createCriteria
method has been deprecated. How to rewrite it as CriteriaQuery
to keep your code simple and not use CriteriaBuilder
.
Solution
Hibernate 5.4 The documentation recommends using the Jakarta Persistence API (
JPA) class. The fact that all methods, including overloads of the method createCriteria that return org.hibernate.Criteria, are deprecated, indirectly means that Hibernate does not want us to use their
org.hibernate.Criteria
interface.
In version 5.4,
the Criteria
interface did not implement a class or interface interface. In short, hibernate sessions
that were once used as Criteria object factories no longer generate them, and
Criteria
may be completely deprecated in future releases.
Second, Hibernate provides useful APIs under the org.hibernate.criterion
package, such as limits, examples, etc. The problem is that all of these classes seem to have only one consumer class of type org.hibernate.Criteria
, which is being deprecated. In other words, if you can’t use org.hibernate.Criteria, then you can’t use org.hibernate.criteria.Restrictions.
All in all, if you have to refactor the above code now, your only option is what’s under javax.persistence.criteria.
Therefore, your only option is to use CriteriaBuilder
and CreateQuery
, as shown below.
CriteriaBuilder cb = sessionFactory.getCurrentSession().getCriteriaBuilder();
Create query
CriteriaQuery<Post> q = cb.createQuery(Post.class)
Root<Post> r = q.from(Post.class);
Predicate[] predicates = new Predicate[2];
predicates[0] = cb.equal(root.get("title"), title);
predicates[1] = cb.equal(root.get("description"), description);
q.select(r).where(predicates);
Query<Post> query = session.createQuery(q);
return query.getSingleResult();
Yes, this code is quite verbose compared to your original code using the Hibernate API. However, one advantage provided by this code is that it is now decoupled from the Hibernate-specific API. Therefore, if you want to migrate to another JPA implementation in the future, you do not need to change the code.