JPA,实体管理器,选择许多列并获取结果列表自定义对象 [英] JPA, Entity manager, select many columns and get result list custom objects
本文介绍了JPA,实体管理器,选择许多列并获取结果列表自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SELECT p.category.id,count( p.id)FROM Product p left join p.category c WHERE p.seller.id =:id GROUP BY c.id
举例:
$ p $ return getEntityManager()。createQuery(SELECT p.category.id,count( p.id)FROM Product p left join p.category c WHERE p.seller.id =:id GROUP BY c.id)。setParameter(id,id).getResultList();
我需要一张带有类别id和产品数量的地图。
$ b $不幸的是,JPA没有提供一个标准方法来检索 Map
中的结果。但是,通过遍历结果列表来手动构建地图很简单: TypedQuery< Object []> q = getEntityManager()。createQuery(
SELECT c.id,count(p.id)+
FROM Product p LEFT JOIN p.category c+
WHERE p。 seller.id =:id+
GROUP BY c.id,Object []。class).setParameter(id,id);
List< Object []> resultList = q.getResultList();
地图< String,Long> resultMap = new HashMap< String,Long>(resultList.size());
for(Object [] result:resultList)
resultMap.put((String)result [0],(Long)result [1]);
How I can get list of custom objects, like results below query:
SELECT p.category.id, count(p.id) FROM Product p left join p.category c WHERE p.seller.id=:id GROUP BY c.id
By example:
return getEntityManager().createQuery("SELECT p.category.id, count(p.id) FROM Product p left join p.category c WHERE p.seller.id=:id GROUP BY c.id").setParameter("id", id).getResultList();
I need a map with category id and number of products in category.
解决方案
Unfortunately, JPA doesn't provide a standard way to retrieve the results in a Map
. However, building up your map manually by walking through the result list is simple enough:
TypedQuery<Object[]> q = getEntityManager().createQuery(
"SELECT c.id, count(p.id) " +
"FROM Product p LEFT JOIN p.category c " +
"WHERE p.seller.id = :id " +
"GROUP BY c.id", Object[].class).setParameter("id", id);
List<Object[]> resultList = q.getResultList();
Map<String, Long> resultMap = new HashMap<String, Long>(resultList.size());
for (Object[] result : resultList)
resultMap.put((String)result[0], (Long)result[1]);
这篇关于JPA,实体管理器,选择许多列并获取结果列表自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文