[英]Hibernate criteria: dto as entity
I have a query built with Hibernate Criteria (I show you only the "main" part): 我有一个使用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));
so I can finally do: 所以我终于可以做:
List<User> users = criteria.list();
Problem comes when I try to load values from this entities. 当我尝试从该实体加载值时,问题就来了。 For example:
例如:
users.get(0).getFirstName();
returns null. 返回null。 So basically the entities created like "dtos" by Transformers.aliasToBean which have received only the "id" by projection are not working as normal entities loaded by get/load/etc.
因此,基本上,由Transformers.aliasToBean创建的像“ dtos”这样的实体通过投影仅接收到“ id”,这些实体不能用作由get / load / etc加载的普通实体。
Is there any way to make these dto "working" as entities? 有什么方法可以使这些dto作为实体“工作”?
Seems passing argument in projectionList is wrong, you need to modify the projectionList like this. 似乎在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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.