1

我有一个使用 Hibernate Criteria 构建的查询(我只向您展示“主要”部分):

Criteria criteria = sessionProvider.get().createCriteria(User.class);
// Add other stuff to the query like joins, group-bys, order-bys etc.
// In the projection list add the "id" of the user.
projectionList.add(Projections.property("id"), "id");
// finally using same entity class User as dto
criteria.setResultTransformer(Transformers.aliasToBean(User.class));

所以我终于可以做到:

List<User> users = criteria.list();

当我尝试从该实体加载值时出现问题。例如:

users.get(0).getFirstName();

返回空值。因此,基本上由 Transformers.aliasToBean 创建的像“dtos”这样的实体仅通过投影接收到“id”,它们不能像 get/load/etc 加载的普通实体那样工作。

有没有办法让这些 dto 作为实体“工作”?

4

1 回答 1

0

似乎在projectionList 中传递参数是错误的,您需要像这样修改projectionList。

Criteria criteria = sessionProvider.get().createCriteria(User.class);
//Add other stuff to the query like joins, group-bys, order-bys etc.

//In the projection list add the columns name which are mapped with the entity
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("id"));
projectionList.add(Projections.property("firstName"));
criteria.setProjection(projectionList);

List<User> results = criteria.list();

//output results
for(User user : results) {
    user.getFirstName();        
}
于 2013-08-01T05:50:47.353 回答