0

I am new to Hibernate Criteria , I found many examples using list. Likes to know how a criteria object can be converted to Employee object. Is it possible for Hibernate Criteria to return a class entity.

Employee emp=  (Employee) session.createCriteria(Employee.class,"a")
.createAlias("a.jobs", "j") 
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("j.active", "1"));

java.lang.ClassCastException: org.hibernate.impl.CriteriaImpl cannot be cast to Employee.

jobs object is one to many relationship, trying to filteractive objects of jobs

2 Answers 2

1

You need to use list() method

List<Employee> result =  (List<Employee>) session.createCriteria(Employee.class,"a")
.createAlias("a.jobs", "j") 
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("j.active", "1")).list();

or uniqueResult(), but you will have an exception, if there is more than one record. If there is not any result uniqueResult() will return null.

Employee result = (Employee) session.createCriteria(Employee.class,"a")
.createAlias("a.jobs", "j") 
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("j.active", "1")).uniqueResult();
Sign up to request clarification or add additional context in comments.

2 Comments

As I am filtering by ID , it will be a single object.
@CorkKochi I update my answer. You can use only those two methods.
0

If there is multiple records but you want single unique result to casting into the model class without using list then you can also use following things :

Employee emp=  (Employee) session.createCriteria(Employee.class,"a")
.createAlias("a.jobs", "j") 
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("j.active", "1")).setMaxResults(1).uniqueResult();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.