Query q = em.createQuery( "SELECT c.id, COUNT(t.id) " + "FROM PubText t " + "JOIN t.comm c " + "WHERE c.element = ?1 " + "GROUP BY c.id"); q.setParameter(1, e); List<?> rl = q.getResultList(); Iterator<?> it = rl.iterator(); HashMap<Long, Long> res = new HashMap<Long, Long>(); while (it.hasNext()) { Object[] n = (Object[]) it.next(); res.put((Long)n[0], (Long)n[1]); } return res;
JPA只为此提供了一个功能 – 构造函数表达式:
Query q = entityManager.createQuery("SELECT NEW com.example.DTO( c.id, COUNT(t.id)) FROM ..."); List<DTO> dtos = q.getResultList();
您的DTO课程可以是POJO.它需要的是一个接受2个Longs的公共构造函数.请注意,您必须在NEWoperator之后提供您班级的完全限定名称.
翻译自:https://stackoverflow.com/questions/15413434/typedquery-instead-of-normal-query-in-jpa