如何使用Criteria返回具有选定列的实体 [英] How to return an entity with chosen columns using Criteria
问题描述
List<用户>
,但只有字段用户标识和名称已填满。那可能吗?类似下面显示的查询: SELECT user.id,user.name FROM user
$ c $ 什么预测是。这里是一个例子:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $>标准cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList (){
.add(Projections.property(id),id)
.add(Projections.property(Name),Name))
.setResultTransformer( Transformers.aliasToBean(User.class));
列表<用户> list = cr.list();
实际上,如果您查看lazy property fetching的文档, p>
避免不必要的列读取的一种不同(更好的方法),至少对于只读事务是使用投影HQL或Criteria查询的特性,这就避免了对构建时字节码处理的需求,而且肯定是一个首选的解决方案。
$ b b
$ b
方式,有一个相关的问题,您可能也感兴趣:
Hibernate通过例子和预测查询
I'm really new with Hibernate. I want a List<User>
using hibernate criteria, but only with fields User id and name filled up. Is that possible? Something like the query shown below:
SELECT user.id, user.name FROM user
Regards.
This is exactly what projections are for. Here is an example:
Criteria cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("Name"), "Name"))
.setResultTransformer(Transformers.aliasToBean(User.class));
List<User> list = cr.list();
In fact, if you look at the documentation for "lazy property fetching" they specifically say:
"A different (better?) way to avoid unnecessary column reads, at least for read-only transactions is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a preferred solution."
By the way, there is a related question that you may also be interested in: Hibernate Query By Example and Projections
这篇关于如何使用Criteria返回具有选定列的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!