i am trying to get some students in Hibernate in many-to-one relationship School-Students. later i am trying to get the Teachers of the school when the students belongs..
here is my code
public ArrayList<Student>search(Date dateBorn)
{
Session session = currentSession();
Criteria criteria = session.createCriteria(Student.class).add(prepareForSelect()).setFetchMode("school",FetchMode.JOIN);
criteria.add(Restrictions.ge("age",dfrom))
.setProjection(addProjection("id","name","lastname","phone","school"))// the only data i need
.setResultTransformer(transformer(Student.class));
ArrayList<Student>students= new ArrayList<Student>(criteria.list());
if (!students.isEmpty())
for (Student student:students) loadTeachersForSchool(session,student,student.getSchool().getId());
return students;
}
private void loadTeachersForSchool(final Session session,final Student student,Integer schoolID)
{
Criteria like = session.createCriteria(Teacher.class).add(prepareForSelect().
add(Restrictions.eq("School.id",schoolID)))
.setProjection(addProjection("id","name","lastname"))//// the only data i need
.setResultTransformer(transFormer(Teacher.class));
student.getSchool().setTeacherList(new java.util.LinkedHashSet<Teacher>(like.list()));
return;
}
everything works like a charm as you can see i am bringing only the ID of the school because is the only thing i need so far and is working
later when i try to set the teacher to the school using this code:
student.getSchool().setTeacherList(new java.util.LinkedHashSet<Teacher>(like.list()));
return;
hibernate generates a SELECT
bringing ALL the SCHOOL
i load the ID
on it because is the only thing i need...
in the line
student.getSchool()
this gets me into trouble because i dont need all this data and is quite long 50 fields
and is degrading my performance what can i do we are using Open Session in View that's why i dont close the session and i using Hibernate 4.2.3 with MySQL 5.
i could get the desired behavior declaring the property as public and accessing directly but of course is not what i want.
student.getSchool().setTeacherList=new java.util.LinkedHashSet<Teacher>(like.list());
please help me.