在JPA中使用TypedQuery而不是普通的Query [英] TypedQuery instead of normal Query in JPA
本文介绍了在JPA中使用TypedQuery而不是普通的Query的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将此查询编写为TypedQuery,并让两个Long运行到一个内部有两个公共Long字段的Object中。
Is it possible to write this Query as a TypedQuery and let the two Long's run into a Object with two public Long fields inside.
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只为此提供了一个功能 - 构造函数表达式:
JPA has a feature just for this - constructor expressions:
Query q = entityManager.createQuery("SELECT NEW com.example.DTO( c.id, COUNT(t.id)) FROM ...");
List<DTO> dtos = q.getResultList();
您的DTO课程可以是POJO。它需要的是一个公共构造函数,接受2 Long
s。请注意,您必须在 NEW
运算符后提供您班级的完全限定名称。
Your DTO class can be a POJO. All it will need is a public constructor accepting 2 Long
s. Please note that you have to provide a fully qualified name of your class after the NEW
operator.
这篇关于在JPA中使用TypedQuery而不是普通的Query的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文