Hasan Tuncay
Hasan Tuncay

Reputation: 1108

TypedQuery instead of normal Query in JPA

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;

Upvotes: 13

Views: 42727

Answers (2)

kostja
kostja

Reputation: 61558

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.

Upvotes: 16

Hasan Tuncay
Hasan Tuncay

Reputation: 1108

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

Upvotes: 14

Related Questions