cz_Nesh。对不起我的第一个答案。我阅读了 Hibernate api 并阅读了一些我发现的 Hibernate 源代码。如果您使用此代码
session.createCriteria(EmpUserImpl.class).list();
它将返回列表 EmpUserImpl。如果您使用此代码
criteria.setProjection(Projections.projectionList()
.add(Projections.groupProperty("company").as("company"))
.add(Projections.property("name").as("name"))
.add(Projections.property("company").as("company")));
List list = criteria.list();
它会返回 List ,不是 List EmpUserImpl 为什么?我看到标准的父类 CriteriaSpecification 我发现。
public interface CriteriaSpecification {
/**
* The alias that refers to the "root" entity of the criteria query.
*/
public static final String ROOT_ALIAS = "this";
/**
* Each row of results is a <tt>Map</tt> from alias to entity instance
*/
public static final ResultTransformer ALIAS_TO_ENTITY_MAP = AliasToEntityMapResultTransformer.INSTANCE;
/**
* Each row of results is an instance of the root entity
*/
public static final ResultTransformer ROOT_ENTITY = RootEntityResultTransformer.INSTANCE;
/**
* Each row of results is a distinct instance of the root entity
*/
public static final ResultTransformer DISTINCT_ROOT_ENTITY = DistinctRootEntityResultTransformer.INSTANCE;
/**
* This result transformer is selected implicitly by calling <tt>setProjection()</tt>
*/
public static final ResultTransformer PROJECTION = PassThroughResultTransformer.INSTANCE;
/**
* Specifies joining to an entity based on an inner join.
*
* @deprecated use {@link org.hibernate.sql.JoinType#INNER_JOIN}
*/
@Deprecated
public static final int INNER_JOIN = JoinType.INNER_JOIN.getJoinTypeValue();
/**
* Specifies joining to an entity based on a full join.
*
* @deprecated use {@link org.hibernate.sql.JoinType#FULL_JOIN}
*/
@Deprecated
public static final int FULL_JOIN = JoinType.FULL_JOIN.getJoinTypeValue();
/**
* Specifies joining to an entity based on a left outer join.
*
* @deprecated use {@link org.hibernate.sql.JoinType#LEFT_OUTER_JOIN}
*/
@Deprecated
public static final int LEFT_JOIN = JoinType.LEFT_OUTER_JOIN.getJoinTypeValue();
}
你能看到 public static final ResultTransformer PROJECTION 吗?它说这个结果转换器是通过调用 setProjection() 隐式选择的,这意味着当你使用条件时。setProjection,结果不会列出 EmpUserImpl,因为 ResultTransformer 从“ROOT_ENTITY”更改为“PROJECTION”。它将由 Projection 打包(如选择名称,oid ..)。所以,如果你想返回 List EmpUserImpl 你需要设置 Projections.property("name").as("name").,(如果你需要 name 只是设置 name)。这是我的代码。
Criteria criteria = session.createCriteria(EmpUserImpl.class);
criteria.setProjection(Projections.projectionList()
.add(Projections.groupProperty("company").as("company"))
.add(Projections.property("name").as("name"))
.add(Projections.property("company").as("company")));
criteria.setResultTransformer(Transformers.aliasToBean(EmpUserImpl.class));
List<EmpUserImpl> list = criteria.list();
for (EmpUserImpl empUserImpl : list) {
System.out.println(empUserImpl.getName());
}
它可以工作。我希望它可以帮助你。