I am new to hibernate and learning about the HCQL(Hibernate Criteria Query language)and tried running below code but getting warning-'The method createCriteria(Class) from the type SharedSessionContract is deprecated'
Criteria myCriteria = session.createCriteria(Employee.class);
Criterion nameCriteria = Restrictions.eq("name", "Amit");
myCriteria.add(nameCriteria);
So I searched on Google and tried the below code but now getting the error in myCriteria.add(nameCriteria) method -'The method add(Criterion) is undefined for the type CriteriaQuery'
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteria = builder.createQuery(Employee.class);
Root<Employee> employeeRoot=criteria.from(Employee.class);
criteria.select(employeeRoot);
Criterion nameCriteria = Restrictions.eq("name", "Amit");
criteria.add(nameCriteria);
Can anyone help me with this? Thank You
As I can see you are trying to combine both APIs. Restrictions.eq()
is a proprietary Hibernate API and you can't use it with CriteriaQuery
. If you want to use JPA Criteria API you could rewrite this query something like this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteria = builder.createQuery(Employee.class);
Root<Employee> employeeRoot = criteria.from(Employee.class);
criteria.select(employeeRoot)
.where(
builder.equal(
employeeRoot.get("name"),
"Amit")
);
TypedQuery<Employee> query = em.createQuery(criteria);
Employee emp = query.getSingleResult();