Search code examples
javahibernatejpa-2.0jpqlhibernate-criteria

How to get all objects using hibernate-core-5.2.0.Final.jar


I did this in earliest vesions of Hibernate as below

sessionFactory.getCurrentSession().createCriteria(TestCase.class).list();

But createCriteria method is deprecated in 5.2.0.Final version:

/** @deprecated */
    @Deprecated
    Criteria createCriteria(Class var1);

What is the alternative solution for this simple example?


Solution

  • Found type-safe solution in this way:

    @PersistenceContext
    protected EntityManager entityManager;
    
    public List<TestCase> findAll() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<TestCase> cq = cb.createQuery(TestCase.class);
    Root<TestCase> from = cq.from(TestCase.class);
    CriteriaQuery<TestCase> all = cq.select(from);
    TypedQuery<TestCase> allQuery = em.createQuery(all);
    return allQuery.getResultList();
    }