如何仅检索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中,我可以通过以下方式检索实体:
query = entityManager.createQuery(从c类中选择c) ;
列表<类别> categories = query.getResultList();
但是,如果我希望检索Category实体的id和name字段,需要类似于 ResultSet
对象,通过它我可以说: rs.getString(name)
和 rs.getString( ID)
。如何通过 JPQL
执行此操作,而不检索整个实体?
基本上,对于如何从一个查询如:从类别c中选择c.id,c.name
?
Query query = session.createQuery(select c.id,c.name from c);
List< Object []> rows = query.list();
返回的数组1-st元素将是id,second - name。
for(Object [] row:rows){
System.out.println(----------- --------);
System.out.println(id:+ row [0]);
System.out.println(name:+ row [1]);
$ b如果你想使用hibernate的Criteria API,你应该使用 Projections 。
使用JPA它将以同样的方式工作:
List< Object []> rows = entityManager.createQuery(queryString).getResultList();
In JPQL, I can retrieve entities by :
query = entityManager.createQuery("select c from Category c");
List<Category> categories = query.getResultList();
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 ?
Basically, for a how to retrieve information from a query like : select c.id,c.name from Category c
?
解决方案 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();
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]);
}
If you want to use hibernate's Criteria API, you should use Projections.
With JPA it will work the same way:
List<Object[]> rows = entityManager.createQuery(queryString).getResultList();
这篇关于如何仅检索JPQL或HQL中实体的某些字段? JPQL或HQL中的ResultSet等价于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!