我有一个简单的Criteria
,用于获取我拥有ID的学生的学校,我只需要学校而不是学生,我有一个简单的编码,例如
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;
}
如您所见,我也检索了学生和学校
,我只需要学校
我的问题是
1).除了 setProjections()
之外,还有一种方法可以仅提取[从数据库中检索] School fields
而不是 Student fields
因为到许多字段,并且在 setProjection
中列出所有字段是一种烦人的行为,并且会影响性能,例如
setProjectionOnlyPropertiesForClass(School.class)
。
2).有任何解决方法。
非常感谢。
最佳答案
问题是您正在查询 Student 对象而不是 School 对象!对应的HQL查询为:
select student
from Student student join student.school
where student.id=:studentId
相反,您应该查询 School 对象:
select school
from School school, Student student
where student.school = school and student.id=:studentId
(也许您应该使用 HQL 而不是标准查询 - 它们更容易编写和理解)。
关于Java Hibernate Criteria 仅返回一个实体字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18983148/