Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative code for createCriteria() method in Hibernate 5.2.2

Tags:

hibernate

In Hibernate 5.2.2 createCriteria() method is deprecated. Please give the alternative solution and code snippet.

Code

Criteria criteria=session.createCriteria(Student3.class);   
List<Student3> studentsNameList= criteria.list();           

        for (Student3 studentName : studentsNameList) {
            System.out.println("Student details - "+studentName.getName()+" -- "+studentName.getEmail());   }   

Searching in google I found that DetachedCriteria can be used instead of createCriteria() but it does not have a list() method

DetachedCriteria detachedCriteria=DetachedCriteria.forClass(Student3.class);
like image 679
Santonu Ghosh Avatar asked Sep 09 '16 16:09

Santonu Ghosh


1 Answers

I just got done fighting the same thing. The Hibernate documentation says to use JPA Criteria. Here is what I came up with...

import javax.persistence.criteria.CriteriaQuery;

CriteriaQuery<Student3> cq = session.getCriteriaBuilder().createQuery(Student3.class);
cq.from(Student3.class);
List<Student3> studentsNameList = session.createQuery(cq).getResultList();

for (Student3 studentName : studentsNameList) {
    System.out.println("Student details - "+studentName.getName()+" -- "+studentName.getEmail());   
}   

Not as elegant, but typed.

--Update-- I have not dove too far into the details yet, but here is how I would go about adding an actual criteria:

import javax.persistence.criteria.CriteriaQuery;
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student3> cq = cb.createQuery(Student3.class);

Root<Student3> studentRoot = cq.from(Student3.class);
ParameterExpression<Integer> id = cb.parameter(Integer.class);

cq.select(studentRoot).where(cb.eq(studentRoot.get("id"),id));

 TypedQuery<Student3> query = em.createQuery(cq);
 query.setParameter(p, 2);
 List<Student3> results = query.getResultList();

Again, I am just learning JPA so there may be an easier way (and I would love to know about it if you find something)

like image 138
bshouse Avatar answered Nov 14 '22 12:11

bshouse