gpt4 book ai didi

java - Hibernate:org.hibernate.criterion.ProjectionList 无法转换为 org.hibernate.Criteria

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:40 36 4
gpt4 key购买 nike

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

ProjectionList cannot be cast to 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());

}

最佳答案

重写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() 方法调用用于将源属性放入正确的 FeatureSearchResult 的属性中。

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

关于java - Hibernate:org.hibernate.criterion.ProjectionList 无法转换为 org.hibernate.Criteria,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21038894/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com