0

我正试图让一些学生在 Hibernate 中建立多对一的关系。后来我试图在学生属于时找到学校的老师。

这是我的代码

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;
}

如您所见,一切都像魅力一样,我只带了学校的身份证,因为这是迄今为止我唯一需要并且正在工作的东西

后来,当我尝试使用此代码将老师设置为学校时:

student.getSchool().setTeacherList(new java.util.LinkedHashSet<Teacher>(like.list()));
return;

hibernate 会生成一个SELECT将所有SCHOOL我加载到ID它的内容,因为这是我唯一需要的东西......

在行中

student.getSchool()

这给我带来了麻烦,因为我不需要所有这些数据并且很长50 fields并且正在降低我的性能我能做什么我们在 View 中使用 Open Session 这就是为什么我不关闭会话并且我使用 Hibernate 4.2.3 和 MySQL 5。

我可以获得所需的行为,将属性声明为公共并直接访问,但当然不是我想要的。

student.getSchool().setTeacherList=new java.util.LinkedHashSet<Teacher>(like.list());

请帮我。

4

1 回答 1

0

解决方案

我决定自己创建一个 School 实例很容易我知道我从休眠中失去了一些好处但我现在不需要它这是我的解决方案。我希望对某人有所帮助。

private void loadTeachersForSchool(final Session session,final Student student,Integer  schoolID)
{
   School school = new School(idSchool);
   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));                
   school.setTeacherList(new java.util.LinkedHashSet<Teacher>(like.list()));
   student.setSchool(school);
  return;
}

这解决了诀窍..我不从 DB 加载学校。

检查重点。

School school = new School(idSchool);//create the school instance and and the teachers
school.setTeacherList(new java.util.LinkedHashSet<Teacher>(like.list()));
student.setSchool(school);//and add all to students
于 2013-07-17T01:38:51.723 回答