2013-09-24 36 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,而不是爲標準的查詢 - 他們是簡單的編寫和理解) 。