【问题标题】:Java Hibernate Criteria returning only one entity fieldsJava Hibernate Criteria 仅返回一个实体字段
【发布时间】:2013-09-24 13:34:50
【问题描述】:

我有一个简单的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;
}

如您所见,我也检索了Student and the School,我只需要School 我的问题是

1)。除了setProjections() 之外,还有一种方法可以提取[从数据库中检索] 仅School fields 而不是Student fields,因为它涉及到许多字段,并且列出setProjection 中的所有字段是一种烦人的方式,并且会影响性​​能像

setProjectionOnlyPropertiesForClass(School.class)

2)。有任何解决方法。

非常感谢。

【问题讨论】:

    标签: java hibernate criteria projection


    【解决方案1】:

    问题是您查询的是学生对象而不是学校对象!对应的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 而不是条件查询 - 它们更易于编写和理解)。

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 2021-07-05
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      相关资源
      最近更新 更多