如何仅检索 JPQL 或 HQL 中实体的某些字段?JPQL 或 HQL 中 ResultSet 的等价物是什么? [英] How to retrieve only certain fields of an entity in JPQL or HQL? What is the equivalent of ResultSet in JPQL or HQL?
问题描述
在 JPQL 中,我可以通过以下方式检索实体:
In JPQL, I can retrieve entities by :
query = entityManager.createQuery("select c from Category c");
List<Category> categories = query.getResultList();
但是,如果我希望检索 Category 实体的 id 和 name 字段(仅),我需要类似 ResultSet
对象的东西,通过它我可以说:rs.getString("name")
和 rs.getString("id")
.如何通过 JPQL
做到这一点,而无需检索整个实体?
But, if I wish to retrieve the id and name fields (only) of the Category entity, I need something like the ResultSet
object, through which I can say : rs.getString("name")
and rs.getString("id")
. How to do this through JPQL
, without retrieving the entire entity ?
基本上,对于如何从如下查询中检索信息:select c.id,c.name from Category c
?
Basically, for a how to retrieve information from a query like : select c.id,c.name from Category c
?
推荐答案
在 HQL 中,您可以使用 list() 函数来获取包含结果行的 Object[] 数组的列表:
In HQL you can use list() function to get a list of Object[] array that contains result rows:
Query query = session.createQuery("select c.id,c.name from Category c");
List<Object[]> rows = query.list();
在返回的数组中,第一个元素将是 id,第二个 - 名称.
in returned array 1-st element will be id, second - name.
for (Object[] row: rows) {
System.out.println(" ------------------- ");
System.out.println("id: " + row[0]);
System.out.println("name: " + row[1]);
}
如果你想使用 hibernate 的 Criteria API,你应该使用 预测.
If you want to use hibernate's Criteria API, you should use Projections.
使用 JPA,它的工作方式相同:
With JPA it will work the same way:
List<Object[]> rows = entityManager.createQuery(queryString).getResultList();
这篇关于如何仅检索 JPQL 或 HQL 中实体的某些字段?JPQL 或 HQL 中 ResultSet 的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!