使用条件API获取两个对象的属性

时间:2012-09-10 11:29:45

标签: hibernate hql criteria-api

使用Criteria API运行HQL查询时获取异常

 org.hibernate.QueryException: could not resolve property: com of: com.data.Collage        at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:44)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:38)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1362)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getPathEntityName(CriteriaQueryTranslator.java:204)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.createCriteriaEntityNameMap(CriteriaQueryTranslator.java:191)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.<init>(CriteriaQueryTranslator.java:81)
    at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:58)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1550)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)

具有以下类定义

class Collage {
int id;
String collageName;
List lstStudent;
}

class Student{
String studentName;
int id;
}

已完成上述类的映射。

现在我想在单个查询中获取拼贴名称和学生姓名,其中我有collageID和StudentID。已使用的Criteria API。

Criteria cr = session.createCriteria("com.data.Collage","collageAlias");
cr.createAlias("com.data.Student","studentAlias");
cr.add(Restrictions.eq("collageAlias.id", "402882c2369bc53901369bc95d5f0137"));
cr.add(Restrictions.eq("studentAlias.id","ff80808134cbe5a10134d14ff20300a9"));

ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("collageAlias.collageName"));
properties.add(Projections.property("studentAlias.studentName"));

cr.setProjection(properties);
List collage_student = cr.list();

我尝试使用Collage.class,删除了拼贴的别名,作为标准API的默认类,但它没有用。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

当你这样做时

cr.createAlias("com.data.Student","studentAlias");

Hibernate自动认为Student是Collage类的字段,因为条件是基于该类构建的。通过创建别名,您可以自动在该特定实体上建立连接。

由于您的Collage类没有名为“com.data.Student”的属性,因此会导致错误。

您应该考虑稍微重构一下代码。如果您希望Collage处理Student个实体列表,请将List lstStudent更改为List<Student> lstStudent。现在,您可以映射类,以便告诉Hibernate两个实体之间的关系:

@Entity
class Collage {
    int id;
    String collageName;
    List<Student> lstStudent;
}

@Entity
class Student{
    String studentName;
    Collage collage;
    int id;
}

Collage getter的List<Student> lstStudent课程中,您将拥有:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "collage")
public List<Student> getStudents() {
    return this.lstStudents;
}

,在Student的{​​{1}}类中,您将拥有:{/ p>

Collage

这基本上允许您在@ManyToOne(fetch = FetchType.LAZY) public Collage getCollage(){ return this.collage; } 类上创建一个条件,并使用Collage列表的别名直接访问:

Students
相关问题