2013-09-24 33 views
0

我有一个简单Criteria所使用的小同学,我有ID的学校里,我只需要学校不是学生,我有一个简单的编码像Java的Hibernate的标准只返回一个实体领域

public School loadSchool(Integer studentID) 
{   
    final Session session = getHibernateTemplate().getSessionFactory().openSession(); 
    final Criteria like = session.createCriteria(Student.class) 
    .add(idEq(studentID)) 
    .setFetchMode("School",FetchMode.JOIN); 
    final School retValue = ((Student)like.uniqueResult()).getSchool(); 
    session.close(); 
    return retValue; 
} 

你可以看到我检索Student and the School以及我只需要School我的问题是

1)。还有比setProjections(),我可以提取物[从数据库中检索]以外的方式只有School fields不是Student fields,因为对许多领域,是一种恼人的列出所有字段setProjection和影响性能类似

setProjectionOnlyPropertiesForClass(School.class)。 2)。有任何解决方法。

非常感谢。

回答

1

问题是您正在查询学生对象而不是学校对象!相应的HQL查询:

select student 
from Student student join student.school 
where student.id=:studentId 

相反,你应该查询学校的对象:

select school 
from School school, Student student 
where student.school = school and student.id=:studentId 

(也许你应该使用HQL,而不是为标准的查询 - 他们是简单的编写和理解) 。