Hibernate:org.hibernate.criterion.ProjectionList无法强制转换为org.hibernate.Criteria

时间:2014-01-10 07:58:08

标签: java hibernate orm hibernate-criteria

如何将Hibernate Criteria中的选定列值分配给bean类?当我尝试将值分配给bean时,它给出了以下错误:

  

ProjectionList无法强制转换为org.hibernate.Criteria。


请参阅下面的代码,其中包含错误:

Criteria criteria = session.createCriteria(PartFeatureVersion.class,"pfv");
criteria.createAlias("pfv.part", "p");
criteria.createAlias("pfv.featureVersion", "fv");
criteria.createAlias("pfv.dateRange", "d");
criteria.createAlias("fv.feature", "f");
criteria.setProjection((Projection) ((Criteria) Projections.projectionList()
        .add(Projections.property("f.name"))
        .add(Projections.property("fv.versionName"))
        .add(Projections.property("d.startDate"))
        .add(Projections.property("d.endDate"))
        .add(Projections.property("fv.featureVersionId")))
        .setResultTransformer(Transformers.aliasToBean(FeatureSearchResult.class)));
criteria.add(Restrictions.eqProperty("pfv.part.id","p.partId"));
criteria.add(Restrictions.eqProperty("pfv.featureVersion.id","fv.featureVersionId"));
criteria.add(Restrictions.eqProperty("pfv.dateRange.id","d.dateRangeId"));
criteria.add(Restrictions.eqProperty("fv.feature.id","f.featureId"));
criteria.add(Restrictions.eq("p.partNbr", partNo));


List list = criteria.list();
                Iterator it = list.iterator();
                while(it.hasNext())
                {
                FeatureSearchResult feature = (FeatureSearchResult)it.next();
                System.out.println(feature.getName());
                System.out.println(feature.getVersionName());

                }

1 个答案:

答案 0 :(得分:3)

criteria.setProjection()代码重写为:

criteria.setProjection(Projections.projectionList()
  .add(Projections.property("f.name").as("name"))
  .add(Projections.property("fv.versionName").as("versionName"))
  .add(Projections.property("d.startDate").as("startDate"))
  .add(Projections.property("d.endDate").as("endDate"))
  .add(Projections.property("fv.featureVersionId").as("featureVersionId")));
criteria.setResultTransformer(Transformers.aliasToBean(FeatureSearchResult.class));

FeatureSearchResult被声明为(只是一个例子,肯定会与真正的定义不同):

class FeatureSearchResult {
  String name;
  String versionName;
  Date startDate;
  Date endDate;
  String featureVersionId;

  // Add getter/setter
}
使用

as()方法调用将source属性放入正确的FeatureSearchResult属性中。

我希望我很清楚,英语不是我的母语。