Getting Exception while running query using Criteria API
org.hibernate.QueryException: could not resolve property: com of: com.data.Collage at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:44)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:38)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1362)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getPathEntityName(CriteriaQueryTranslator.java:204)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.createCriteriaEntityNameMap(CriteriaQueryTranslator.java:191)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.<init>(CriteriaQueryTranslator.java:81)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:58)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1550)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
Having class definitions as follow
class Collage {
int id;
String collageName;
List lstStudent;
}
class Student{
String studentName;
int id;
}
Have done mapping for above classes.
Now I am trying to fetch collage name and student name in single query where I have collageID and StudentID with me. Used Criteria API for this.
Criteria cr = session.createCriteria("com.data.Collage","collageAlias");
cr.createAlias("com.data.Student","studentAlias");
cr.add(Restrictions.eq("collageAlias.id", "402882c2369bc53901369bc95d5f0137"));
cr.add(Restrictions.eq("studentAlias.id","ff80808134cbe5a10134d14ff20300a9"));
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("collageAlias.collageName"));
properties.add(Projections.property("studentAlias.studentName"));
cr.setProjection(properties);
List collage_student = cr.list();
I have try with Collage.class, removed alias name for collage as t’s default class for criteria API, But it didn’t work.
Any suggestion?
When you do
Hibernate automatically thinks that Student is a field of the
Collageclass, as the criteria is built on that class. By creating an alias you automatically make a join on that particular entity.Since your
Collageclass does not have a property named “com.data.Student” it causes your error.You should consider refactoring your code a little bit. If you want the
Collageto handle a list ofStudententities, changeList lstStudenttoList<Student> lstStudent. Now, you can map the classes so that you tell Hibernate the relation between the 2 entities:In the
Collageclass for theList<Student> lstStudentgetter you will have:, while in the
Studentclass for the getter ofCollageyou will have:This basically allows you to create a Criteria on the
Collageclass and have direct access with an alias to its list ofStudents: