Search code examples
springspring-boothibernatecriteriacriteriaquery

Criteria API deprecated, how to convert ti CriteriaQuery instead?


I am migrating an old existing project to Springboot. I have following method:

public List<T> findAll(Class<?> clazz) {
    Criteria search = entityManager.unwrap(Session.class).createCriteria(clazz);
    List<T> entities = search.list();
    return entities;
}

And another one:

public County findByName(String name) {
    Criteria search = entityManager.unwrap(Session.class).createCriteria(County.class).add(Restrictions.eq("county", name));

    County county = (County) search.uniqueResult();

    return county;
}

This works but when i run the project I get following warning: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead

How can i convert it to using javax.persistence.criteria.CriteriaQuery and still be able to receive the same result? I have never been using both of these APIs.

Thank for the help!


Solution

  • find all:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Country> cq = cb.createQuery(Country.class);
    
    Root<Country> rootCountry= cq.from(Country.class);
    cq.select(rootCountry);
    
    List<Country> result = entityManager.createQuery(cq).getResultList();
    

    find by name:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Country> cq = cb.createQuery(Country.class);
    
    Root<Country> rootCountry= cq.from(Country.class);
    cq.select(rootCountry);
    cq.where(cb.equal(rootCountry.get(Country_.name),NAME))
    // if you don't use metamodel (although it is recommended) -> cq.where(cb.equal(rootCountry.get("name"),NAME))
    
    Country result = entityManager.createQuery(cq).getSingleResult();
    

    Can you read more about this in this link https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/querycriteria.html