Java Hibernate条件只返回一个实体字段
我有一个简单的Java Hibernate条件只返回一个实体字段,java,hibernate,criteria,projection,Java,Hibernate,Criteria,Projection,我有一个简单的标准,用于获取我有ID的学生的学校我只需要学校而不是学生我有一个简单的编码 public School loadSchool(Integer studentID) { final Session session = getHibernateTemplate().getSessionFactory().openSession(); final Criteria like = session.createCriteria(Student.class)
标准
,用于获取我有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()
之外,还有一种方法,我可以提取[从数据库中检索]只有学校字段
而不是学生字段
,因为这些字段太多了,列出setProjection
中的所有字段是一种烦人的事情,会影响性能
setProjectionOnlyPropertiesForClass(School.class)
2) 。有任何解决办法
非常感谢。问题是您查询的是学生对象而不是学校对象!相应的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而不是标准查询,因为它们更易于编写和理解)