TypedQuery instead of normal Query in JPA

核能气质少年 提交于 2019-12-03 07:26:05

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();

Your DTO class can be a POJO. All it will need is a public constructor accepting 2 Longs. Please note that you have to provide a fully qualified name of your class after the NEWoperator.

New code looks like this now. Thanks for you help.

    TypedQuery<CommUsed> q = em.createQuery(
        "SELECT new CommUsed(c.id,COUNT(t.id)) " +
        "FROM PubText t " +
        "JOIN t.comm c " +
        "WHERE c.element = ?1 " +
        "GROUP BY c.id", CommUsed.class);
    q.setParameter(1, e);
    HashMap<Long, Long> res = new HashMap<Long, Long>();
    for (CommUsed u : q.getResultList())
        res.put(u.commID, u.cnt);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!